using System.Text.Json;

namespace CalledIt.Seeder;

/// <summary>
/// Loads match data directly from the football-data.org v4 API.
/// Requires an API key (free tier available at football-data.org).
/// </summary>
public sealed class FootballDataApiMatchDataSource(
    string apiKey,
    string competitionCode,
    string season) : IMatchDataSource
{
    private const string BaseUrl = "https://api.football-data.org/v4";

    public async Task<FootballDataResponse> LoadAsync()
    {
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("X-Auth-Token", apiKey);

        var url = $"{BaseUrl}/competitions/{competitionCode}/matches?season={season}";
        Console.WriteLine($"  Fetching matches from API: {url}");

        var json = await client.GetStringAsync(url);

        return JsonSerializer.Deserialize<FootballDataResponse>(json)
            ?? throw new InvalidOperationException("Failed to deserialize API response.");
    }
}
