<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Tribunal;
use App\Models\TribunalVote;

class CloseTribunals extends Command
{
    protected $signature   = 'tribunals:close';
    protected $description = 'Süresi dolan mahkemeleri kapat ve kazananı belirle';

    public function handle(): int
    {
        $expired = Tribunal::where('status', 'open')
            ->where('closes_at', '<=', now())
            ->get();

        if ($expired->isEmpty()) {
            $this->info('Kapatılacak mahkeme yok.');
            return 0;
        }

        foreach ($expired as $tribunal) {
            $sides = $tribunal->allSides();
            $counts = [];
            foreach (array_keys($sides) as $side) {
                $counts[$side] = TribunalVote::where('tribunal_id', $tribunal->id)
                    ->where('side', $side)
                    ->count();
            }

            arsort($counts);
            $topSide   = array_key_first($counts);
            $topCount  = $counts[$topSide];
            $allEqual  = count(array_unique(array_values($counts))) === 1 && array_sum($counts) > 0;

            $verdict = null;
            if (!$allEqual && $topCount > 0) {
                $verdict = $sides[$topSide] ?? $topSide;
            }

            $tribunal->update([
                'status'  => 'closed',
                'verdict' => $verdict,
            ]);

            $this->line("Kapatıldı: #{$tribunal->id} — Karar: " . ($verdict ?? 'Beraberlik'));
        }

        $this->info("{$expired->count()} mahkeme kapatıldı.");
        return 0;
    }
}
