using Microsoft.EntityFrameworkCore;

namespace Backend.Data;

public static partial class SeedDataBootstrapper
{
    public static async Task EnsureAsync(AwardsDbContext db)
    {
        await EnsureSiteSettingsAsync(db);

        var seasons = await db.Seasons.ToDictionaryAsync(item => item.Year);
        if (seasons.Count == 0)
        {
            return;
        }

        foreach (var season in seasons.Values)
        {
            await EnsureCategoriesAsync(db, season);
        }

        if (seasons.TryGetValue(2026, out var currentSeason))
        {
            await EnsureCandidatesAsync(db, currentSeason, SeedCatalog.CurrentCandidateSeeds);
            await EnsureSeedOperationalDataAsync(db, currentSeason);
        }

        foreach (var year in new[] { 2025, 2024, 2023 })
        {
            if (!seasons.TryGetValue(year, out var season))
            {
                continue;
            }

            var winners = SeedCatalog.WinnerSeeds.Where(item => item.Year == year).ToArray();
            await EnsureCandidatesAsync(db, season, winners.Select(item => new CandidateSeed(item.CategorySlug, item.DisplayName, item.ChannelSlug, item.Platform)).ToArray());
            await EnsureWinnersAsync(db, season, winners);
        }

        await db.SaveChangesAsync();
    }
}
