<?php

declare(strict_types=1);

namespace App\Framework\Database\Profiling\Reports;

/**
 * Slow query analysis report
 */
final readonly class SlowQueryReport
{
    public function __construct(
        public array $slowQueries
    ) {
    }

    /**
     * Get top slow queries
     */
    public function getTopSlowQueries(int $limit = 10): array
    {
        return array_slice($this->slowQueries, 0, $limit);
    }

    /**
     * Group slow queries by pattern
     */
    public function getSlowQueryPatterns(): array
    {
        $patterns = [];

        foreach ($this->slowQueries as $entry) {
            $profile = $entry['profile'];
            $normalizedSql = $profile->getNormalizedSql();

            if (! isset($patterns[$normalizedSql])) {
                $patterns[$normalizedSql] = [
                    'pattern' => $normalizedSql,
                    'count' => 0,
                    'total_time_ms' => 0,
                    'avg_time_ms' => 0,
                    'max_time_ms' => 0,
                    'examples' => [],
                ];
            }

            $patterns[$normalizedSql]['count']++;
            $timeMs = $profile->executionTime->toMilliseconds();
            $patterns[$normalizedSql]['total_time_ms'] += $timeMs;
            $patterns[$normalizedSql]['max_time_ms'] = max($patterns[$normalizedSql]['max_time_ms'], $timeMs);

            if (count($patterns[$normalizedSql]['examples']) < 3) {
                $patterns[$normalizedSql]['examples'][] = [
                    'connection' => $entry['connection'],
                    'profile_id' => $profile->id,
                    'execution_time_ms' => $timeMs,
                    'sql' => substr($profile->sql, 0, 200) . '...',
                ];
            }
        }

        // Calculate averages and sort by frequency
        foreach ($patterns as &$pattern) {
            $pattern['avg_time_ms'] = $pattern['total_time_ms'] / $pattern['count'];
        }

        uasort($patterns, fn ($a, $b) => $b['count'] <=> $a['count']);

        return $patterns;
    }

    /**
     * Convert to array
     */
    public function toArray(): array
    {
        return [
            'total_slow_queries' => count($this->slowQueries),
            'top_slow_queries' => $this->getTopSlowQueries(),
            'slow_query_patterns' => $this->getSlowQueryPatterns(),
        ];
    }
}
