<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class QueryAuditCommand extends Command
{
    protected $signature = 'onox:query-audit {--url=}';

    protected $description = 'Profile DB queries for given URL (N+1 detection)';

    public function handle(): int
    {
        $url = $this->option('url');
        if (! $url) {
            $this->error('Provide --url=/admin/dashboard');

            return 1;
        }

        $queries = [];
        DB::listen(function ($query) use (&$queries) {
            $queries[] = [
                'sql' => $query->sql,
                'bindings' => $query->bindings,
                'time' => $query->time,
            ];
        });

        // Internal simulation: trigger route listing as a proxy for URL profiling.
        // For real HTTP profiling, run the app under TELESCOPE or enable DB::listen
        // in middleware and hit the URL via curl/browser with QUERY_LOG=true.
        $this->info("Simulating internal request for: {$url}");
        $this->call('route:list', ['--path' => ltrim($url, '/')]);

        $this->info('Total queries: '.count($queries));

        $duplicates = [];
        foreach ($queries as $q) {
            $key = $q['sql'];
            $duplicates[$key] = ($duplicates[$key] ?? 0) + 1;
        }

        $potentialNPlusOne = array_filter($duplicates, fn ($count) => $count > 5);
        if (! empty($potentialNPlusOne)) {
            $this->warn('Potential N+1 queries detected:');
            foreach ($potentialNPlusOne as $sql => $count) {
                $this->line("  [{$count}x] ".substr($sql, 0, 100));
            }
        } else {
            $this->line('  No N+1 patterns detected (threshold: >5 identical queries).');
        }

        $slow = array_filter($queries, fn ($q) => $q['time'] > 100);
        if (! empty($slow)) {
            $this->warn('Slow queries (>100ms):');
            foreach ($slow as $q) {
                $this->line("  [{$q['time']}ms] ".substr($q['sql'], 0, 100));
            }
        } else {
            $this->line('  No slow queries (>100ms) detected.');
        }

        return 0;
    }
}
