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

namespace Backend.Endpoints;

public static partial class AdminModerationEndpoints
{
    private static async Task<IResult> DeleteClip(
        HttpContext context,
        int clipId,
        AwardsDbContext db,
        IAdminAuditService adminAuditService)
    {
        var session = AdminEndpointConventions.CurrentSession(context);
        var clip = await db.ClipSubmissions.FirstOrDefaultAsync(item => item.Id == clipId);
        if (clip is null)
        {
            return Results.NotFound();
        }

        db.ClipSubmissions.Remove(clip);
        adminAuditService.AddEntry(
            session.TwitchUserId,
            "clip.delete",
            "clip",
            clip.Id.ToString(),
            $"Clip-Einreichung von {clip.SubmittedByTwitchId} wurde entfernt.",
            new { clip.Platform },
            RequestMetadataReader.Read(context));

        await db.SaveChangesAsync(context.RequestAborted);
        return Results.Ok(new { deleted = true, clipId });
    }

    private static async Task<IResult> UpdateClipStatus(
        HttpContext context,
        int clipId,
        UpdateClipStatusRequest request,
        AwardsDbContext db,
        IAdminAuditService adminAuditService)
    {
        var session = AdminEndpointConventions.CurrentSession(context);
        var clip = await db.ClipSubmissions.FirstOrDefaultAsync(item => item.Id == clipId);
        if (clip is null)
        {
            return Results.NotFound();
        }

        var normalizedStatus = string.IsNullOrWhiteSpace(request.Status)
            ? "pending"
            : request.Status.Trim().ToLowerInvariant();

        if (normalizedStatus is not ("pending" or "approved" or "rejected"))
        {
            return Results.BadRequest(new { message = "Clip status must be pending, approved or rejected." });
        }

        clip.Status = normalizedStatus;
        clip.ReviewNote = string.IsNullOrWhiteSpace(request.ReviewNote) ? null : request.ReviewNote.Trim();
        if (normalizedStatus == "pending")
        {
            clip.ReviewedAt = null;
            clip.ReviewedByTwitchId = null;
        }
        else
        {
            clip.ReviewedAt = DateTimeOffset.UtcNow;
            clip.ReviewedByTwitchId = session.TwitchUserId;
        }

        adminAuditService.AddEntry(
            session.TwitchUserId,
            "clip.status.update",
            "clip",
            clip.Id.ToString(),
            $"Clip-Einreichung {clip.Id} wurde auf {clip.Status} gesetzt.",
            new { clip.Status, clip.ReviewNote },
            RequestMetadataReader.Read(context));

        await db.SaveChangesAsync(context.RequestAborted);
        return Results.Ok(new { saved = true, clipId = clip.Id, status = clip.Status });
    }
}
