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

namespace Backend.Endpoints;

public static partial class AuthEndpoints
{
    private static async Task<IResult> DeleteMyParticipationData(
        HttpContext context,
        AwardsDbContext db,
        IUserSessionService userSessionService)
    {
        var session = await userSessionService.ResolveSessionAsync(context, context.RequestAborted);
        if (session is null)
        {
            return Results.Unauthorized();
        }

        var teamMember = await FindTeamMemberForSessionAsync(db, session, context.RequestAborted);
        if (teamMember is not null)
        {
            return Results.Json(
                new { message = "Team-Accounts werden nicht ueber die automatische Teilnahme-Datenloeschung entfernt." },
                statusCode: StatusCodes.Status403Forbidden);
        }

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

        var ballotIds = await db.VoteBallots
            .Where(item => item.SubmittedByTwitchId == twitchUserId)
            .Select(item => item.Id)
            .ToArrayAsync(context.RequestAborted);

        var deletedVoteEntries = ballotIds.Length == 0
            ? 0
            : await db.VoteEntries
                .Where(item => ballotIds.Contains(item.BallotId))
                .ExecuteDeleteAsync(context.RequestAborted);

        var deletedBallots = await db.VoteBallots
            .Where(item => item.SubmittedByTwitchId == twitchUserId)
            .ExecuteDeleteAsync(context.RequestAborted);

        var deletedNominations = await db.Nominations
            .Where(item => item.SubmittedByTwitchId == twitchUserId)
            .ExecuteDeleteAsync(context.RequestAborted);

        var deletedClips = await db.ClipSubmissions
            .Where(item => item.SubmittedByTwitchId == twitchUserId)
            .ExecuteDeleteAsync(context.RequestAborted);

        var deletedRiskFlags = await db.RiskFlags
            .Where(item => item.TwitchUserId == twitchUserId)
            .ExecuteDeleteAsync(context.RequestAborted);

        var disabledSessions = await db.UserSessions
            .Where(item => item.TwitchUserId == twitchUserId)
            .ExecuteUpdateAsync(
                setters => setters.SetProperty(item => item.IsActive, false),
                context.RequestAborted);

        await transaction.CommitAsync(context.RequestAborted);

        return Results.Ok(new
        {
            deleted = true,
            twitchUserId,
            deletedVoteEntries,
            deletedBallots,
            deletedNominations,
            deletedClips,
            deletedRiskFlags,
            disabledSessions,
        });
    }
}
