using Backend.Data;
using Microsoft.EntityFrameworkCore;

namespace Backend.Endpoints;

public static partial class AdminSeasonManagementEndpoints
{
    private sealed record SeasonDeletionSummary(
        int DeletedVoteEntries,
        int DeletedBallots,
        int DeletedResults,
        int DeletedNominations,
        int DeletedClips,
        int DeletedRiskFlags,
        int DeletedCandidates,
        int DeletedCategories);

    private static async Task<SeasonDeletionSummary> DeleteSeasonRelationsAsync(
        AwardsDbContext db,
        int seasonId,
        CancellationToken cancellationToken)
    {
        var ballotIds = await db.VoteBallots
            .Where(item => item.SeasonId == seasonId)
            .Select(item => item.Id)
            .ToArrayAsync(cancellationToken);

        var deletedVoteEntries = ballotIds.Length == 0
            ? 0
            : await db.VoteEntries
                .Where(item => ballotIds.Contains(item.BallotId))
                .ExecuteDeleteAsync(cancellationToken);
        var deletedBallots = await db.VoteBallots
            .Where(item => item.SeasonId == seasonId)
            .ExecuteDeleteAsync(cancellationToken);
        var deletedResults = await db.Results
            .Where(item => item.SeasonId == seasonId)
            .ExecuteDeleteAsync(cancellationToken);
        var deletedNominations = await db.Nominations
            .Where(item => item.SeasonId == seasonId)
            .ExecuteDeleteAsync(cancellationToken);
        var deletedClips = await db.ClipSubmissions
            .Where(item => item.SeasonId == seasonId)
            .ExecuteDeleteAsync(cancellationToken);
        var deletedRiskFlags = await db.RiskFlags
            .Where(item => item.SeasonId == seasonId)
            .ExecuteDeleteAsync(cancellationToken);
        var deletedCandidates = await db.Candidates
            .Where(item => item.SeasonId == seasonId)
            .ExecuteDeleteAsync(cancellationToken);
        var deletedCategories = await db.Categories
            .Where(item => item.SeasonId == seasonId)
            .ExecuteDeleteAsync(cancellationToken);

        return new SeasonDeletionSummary(
            deletedVoteEntries,
            deletedBallots,
            deletedResults,
            deletedNominations,
            deletedClips,
            deletedRiskFlags,
            deletedCandidates,
            deletedCategories);
    }
}
