<?php

namespace App\Console\Commands;

use App\Models\Election;
use App\Services\Elections\ElectionStateService;
use Illuminate\Console\Command;

class OpenElectionVoting extends Command
{
    protected $signature = 'elections:open-voting';
    protected $description = 'Auto-open voting for elections whose voting_start_at has passed';

    public function handle(ElectionStateService $stateService): int
    {
        $this->info('Checking for elections to open voting...');

        $elections = Election::where('status', Election::STATUS_NOMINATION_CLOSED)
            ->whereNotNull('voting_start_at')
            ->where('voting_start_at', '<=', now())
            ->get();

        $count = 0;
        foreach ($elections as $election) {
            try {
                $stateService->transition($election, Election::STATUS_VOTING_OPEN);
                $count++;
                $this->line("  ✓ Opened voting: {$election->title}");
            } catch (\Throwable $e) {
                $this->error("  ✗ Failed for '{$election->title}': {$e->getMessage()}");
            }
        }

        $this->info("Opened voting for {$count} election(s).");

        return self::SUCCESS;
    }
}
