<?php

namespace App\Console\Commands;

use App\Http\Controllers\Api\BetController;
use App\Services\OddsApiService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class SyncOdds extends Command
{
    protected $signature   = 'odds:sync {--scores : Also sync live scores} {--settle : Settle resolved sport bets} {--sport= : Sync only one sport type}';
    protected $description = 'Sync odds and live scores from TheOddsAPI, then settle resolved sport bets';

    public function handle(OddsApiService $oddsApi): int
    {
        if (!$oddsApi->hasKey()) {
            $this->warn('TheOddsAPI key not configured in settings. Skipping sync.');
            return self::SUCCESS;
        }

        $sport = $this->option('sport');

        if ($sport) {
            $this->info("Syncing odds for sport: {$sport}");
            $sportKeys = $oddsApi->sportKeys[$sport] ?? [];
            $total = 0;
            foreach ($sportKeys as $apiKey => $meta) {
                $events = $oddsApi->getOdds($apiKey);
                if ($events) {
                    $n = $oddsApi->syncOddsToDatabase($events, $sport, $meta['league'], $meta['country']);
                    $total += $n;
                    $this->line("  {$meta['country']} / {$meta['league']}: {$n} events");
                }
            }
            $this->info("Synced {$total} total events.");
        } else {
            $this->info('Syncing all sports odds...');
            $results = $oddsApi->syncAll();
            foreach ($results as $line) {
                $this->line($line);
            }
        }

        $remaining = $oddsApi->getRemainingRequests();
        if ($remaining >= 0) {
            $this->comment("API credits remaining: {$remaining}");
        }

        Cache::put('odds_last_updated', now()->toISOString(), 3600);

        if ($this->option('scores') || $this->option('settle')) {
            $this->info('Syncing live scores...');
            $sportsToSync = $sport
                ? [$sport => $oddsApi->sportKeys[$sport] ?? []]
                : $oddsApi->sportKeys;

            $scoreCount = 0;
            foreach ($sportsToSync as $sportType => $leagues) {
                foreach ($leagues as $apiKey => $meta) {
                    $scores = $oddsApi->getScores($apiKey, daysFrom: 1);
                    if ($scores) {
                        $n = $oddsApi->syncScoresToDatabase($scores);
                        $scoreCount += $n;
                    }
                }
            }
            $this->info("Updated {$scoreCount} live scores.");
        }

        if ($this->option('settle')) {
            $this->info('Settling resolved sport bets...');
            $betController = app(BetController::class);
            $settled = $betController->settleSportBets();
            $this->info("Settled {$settled} sport bets.");
        }

        return self::SUCCESS;
    }
}
