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

namespace Backend.Endpoints;

public static partial class AdminSeasonManagementEndpoints
{
    private static async Task<IResult> DeleteSeason(
        HttpContext context,
        int seasonId,
        AwardsDbContext db,
        IAdminAuditService adminAuditService)
    {
        var session = AdminEndpointConventions.CurrentSession(context);
        var season = await db.Seasons.FirstOrDefaultAsync(item => item.Id == seasonId);
        if (season is null)
        {
            return Results.NotFound();
        }

        if (season.IsCurrent)
        {
            return Results.BadRequest(new { message = "Das öffentlich aktive Award-Jahr kann nicht gelöscht werden. Schalte zuerst ein anderes Jahr öffentlich." });
        }

        await using var transaction = await db.Database.BeginTransactionAsync(context.RequestAborted);

        var deletionSummary = await DeleteSeasonRelationsAsync(db, seasonId, context.RequestAborted);

        db.Seasons.Remove(season);
        adminAuditService.AddEntry(
            session.TwitchUserId,
            "season.delete",
            "season",
            season.Id.ToString(),
            $"Season {season.Year} wurde gelöscht.",
            new
            {
                season.Year,
                deletionSummary.DeletedVoteEntries,
                deletionSummary.DeletedBallots,
                deletionSummary.DeletedResults,
                deletionSummary.DeletedNominations,
                deletionSummary.DeletedClips,
                deletionSummary.DeletedRiskFlags,
                deletionSummary.DeletedCandidates,
                deletionSummary.DeletedCategories,
            },
            RequestMetadataReader.Read(context));

        await db.SaveChangesAsync(context.RequestAborted);
        await transaction.CommitAsync(context.RequestAborted);

        return Results.Ok(new
        {
            deleted = true,
            seasonId,
            season.Year,
            deletedVoteEntries = deletionSummary.DeletedVoteEntries,
            deletedBallots = deletionSummary.DeletedBallots,
            deletedResults = deletionSummary.DeletedResults,
            deletedNominations = deletionSummary.DeletedNominations,
            deletedClips = deletionSummary.DeletedClips,
            deletedRiskFlags = deletionSummary.DeletedRiskFlags,
            deletedCandidates = deletionSummary.DeletedCandidates,
            deletedCategories = deletionSummary.DeletedCategories,
        });
    }
}
