<?php

namespace App\Filament\Resources\SportMatchResource\Pages;

use App\Filament\Resources\SportMatchResource;
use App\Services\OddsApiService;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Support\Facades\Cache;

class ListSportMatches extends ListRecords
{
    protected static string $resource = SportMatchResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\Action::make('syncOdds')
                ->label('Sync Odds')
                ->icon('heroicon-o-arrow-path')
                ->action(function (): void {
                    $service = app(OddsApiService::class);

                    if (!$service->hasKey()) {
                        Notification::make()->title('TheOddsAPI is not configured.')->danger()->send();
                        return;
                    }

                    $results = $service->syncAll();
                    Cache::put('odds_last_updated', now()->toISOString(), 3600);

                    Notification::make()
                        ->title('Odds sync completed.')
                        ->body(implode("\n", $results))
                        ->success()
                        ->send();
                }),
            Actions\Action::make('syncScores')
                ->label('Sync Scores')
                ->icon('heroicon-o-bolt')
                ->action(function (): void {
                    $service = app(OddsApiService::class);

                    if (!$service->hasKey()) {
                        Notification::make()->title('TheOddsAPI is not configured.')->danger()->send();
                        return;
                    }

                    $updated = 0;
                    foreach ($service->sportKeys as $leagues) {
                        foreach (array_keys($leagues) as $sportKey) {
                            $scores = $service->getScores($sportKey, daysFrom: 1);
                            if ($scores) {
                                $updated += $service->syncScoresToDatabase($scores);
                            }
                        }
                    }

                    Cache::put('scores_last_updated', now()->toISOString(), 300);

                    Notification::make()
                        ->title("Updated {$updated} score rows.")
                        ->success()
                        ->send();
                }),
            Actions\CreateAction::make(),
        ];
    }
}
