<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Domain\Account\Models\Account;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class PerformanceBenchmarkCommand extends Command
{
    protected $signature = 'onox:benchmark {--rounds=100}';

    protected $description = 'DB sorguları için p50/p95/p99 latency benchmark çalıştırır';

    public function handle(): int
    {
        $rounds = (int) $this->option('rounds');
        $this->info("Benchmark başlıyor — her test {$rounds} tur çalışacak...");
        $this->newLine();

        $tests = [
            'Account::with(user, package) limit(25)' => function () {
                Account::with('owner:id,name,email', 'package:id,name')->limit(25)->get();
            },
            'Dashboard stats (groupBy status)' => function () {
                Account::groupBy('status')
                    ->select('status', DB::raw('count(*) as c'))
                    ->get();
            },
            'Audit log (last 100 rows)' => function () {
                DB::table('audit_log')->latest()->limit(100)->get();
            },
        ];

        $rows = [];
        foreach ($tests as $name => $closure) {
            $times = [];
            for ($i = 0; $i < $rounds; $i++) {
                $start = microtime(true);
                $closure();
                $times[] = (microtime(true) - $start) * 1000;
            }

            sort($times);
            $avg = array_sum($times) / count($times);
            $p50 = $times[(int) ($rounds * 0.50)];
            $p95 = $times[(int) ($rounds * 0.95)];
            $p99 = $times[(int) ($rounds * 0.99)];

            $rows[] = [$name, sprintf('%.2f', $avg), sprintf('%.2f', $p50), sprintf('%.2f', $p95), sprintf('%.2f', $p99)];
        }

        $this->table(
            ['Test', 'avg ms', 'p50 ms', 'p95 ms', 'p99 ms'],
            $rows,
        );

        $this->newLine();
        $this->info('Benchmark tamamlandı.');

        return 0;
    }
}
