<?php

namespace App\Commands;

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

class FootballSyncLeague extends BaseCommand
{
    protected $group = 'Football';
    protected $name = 'football:sync-league';
    protected $description = 'Sync teams and fixtures for a league (API league id)';
    protected $usage = 'football:sync-league <apiLeagueId> [from] [to] [--force]';

    public function run(array $params)
    {
        $apiLeagueId = (int) ($params[0] ?? CLI::getOption('league') ?? 0);
        if ($apiLeagueId <= 0) {
            CLI::error('Usage: php spark football:sync-league <apiLeagueId> [from Y-m-d] [to Y-m-d]');
            return EXIT_ERROR;
        }

        $from = $params[1] ?? date('Y-m-d');
        $to = $params[2] ?? date('Y-m-d', strtotime('+14 days'));
        $force = CLI::getOption('force') !== null;

        try {
            $sync = new FootballLeagueSync();
            $result = $sync->syncByApiLeagueId($apiLeagueId, $from, $to, $force);
            CLI::write(json_encode($result, JSON_PRETTY_PRINT), 'green');
        } catch (\Throwable $e) {
            CLI::error($e->getMessage());
            return EXIT_ERROR;
        }

        return EXIT_SUCCESS;
    }
}
