<?php

namespace App\Console\Commands;

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

class OpenElectionNominations extends Command
{
    protected $signature = 'elections:open-nominations';
    protected $description = 'Auto-open nominations for published elections whose nomination_start_at has passed';

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

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

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

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

        return self::SUCCESS;
    }
}
