using Backend.Common;
using Backend.Contracts;
using Backend.Data;
using Microsoft.EntityFrameworkCore;

namespace Backend.Endpoints;

public static partial class PublicEndpoints
{
    private static async Task<IResult> GetWinnerArchive(int year, AwardsDbContext db)
    {
        var season = await db.Seasons
            .AsNoTracking()
            .Where(item => item.Year == year)
            .Select(item => new { item.Id, item.Year, item.IsCurrent, item.CurrentPhase })
            .FirstOrDefaultAsync();
        if (season is null)
        {
            return Results.NotFound();
        }

        if (season.IsCurrent && !CanExposeCurrentSeasonWinners(season.CurrentPhase))
        {
            return Results.Ok(new WinnerArchiveResponse(year, []));
        }

        var winnerRows = await db.Results
            .AsNoTracking()
            .Include(result => result.Candidate)
            .Where(result => result.SeasonId == season.Id)
            .OrderBy(result => result.CategoryName)
            .Select(result => new
            {
                result.CategoryName,
                WinnerName = result.Candidate.DisplayName,
                WinnerSlug = result.Candidate.ChannelSlug,
                WinnerPlatform = result.Candidate.Platform,
            })
            .ToArrayAsync();

        var items = winnerRows
            .Select(result => new WinnerArchiveItemDto(
                result.CategoryName,
                result.WinnerName,
                result.WinnerSlug,
                result.WinnerPlatform,
                SeasonMappings.BuildProfileUrl(result.WinnerPlatform, result.WinnerSlug)))
            .ToArray();

        return Results.Ok(new WinnerArchiveResponse(year, items));
    }

    private static bool CanExposeCurrentSeasonWinners(string currentPhase)
    {
        var phaseKey = SeasonMappings.NormalizePhaseKey(currentPhase);
        return phaseKey is "completed";
    }
}
