<?php

namespace App\Commands;

use App\Libraries\FootballFixturesDailySync;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

class FootballSyncFixturesDaily extends BaseCommand
{
    protected $group = 'Football';
    protected $name = 'football:sync-fixtures-daily';
    protected $description = 'Refresh cached fixtures for all leagues (run daily at midnight EAT)';
    protected $usage = 'football:sync-fixtures-daily [daysAhead]';

    public function run(array $params)
    {
        set_time_limit(0);
        $daysAhead = (int) ($params[0] ?? 14);

        try {
            CLI::write('Syncing fixtures for all leagues (this uses API quota)...', 'yellow');
            $result = (new FootballFixturesDailySync())->syncAll($daysAhead);
            CLI::write("Leagues processed: {$result['leagues']}", 'green');
            CLI::write("Fixture rows upserted: {$result['fixtures']}", 'green');
            CLI::write("Cache window: {$result['from']} → {$result['to']}", 'green');

            foreach ($result['errors'] as $err) {
                CLI::write($err, 'yellow');
            }
        } catch (\Throwable $e) {
            CLI::error($e->getMessage());
            return EXIT_ERROR;
        }

        return EXIT_SUCCESS;
    }
}
