using System.Security.Claims;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using TrackQrApi.Data;
using TrackQrApi.Features.Auth.Common;

namespace TrackQrApi.Features.QRCodes.Endpoints;

public class DeleteQRCodeRequest
{
    public Guid WorkspaceId { get; set; }
    public Guid Id { get; set; }
}

public class DeleteQRCodeEndpoint(AppDbContext db)
    : Endpoint<DeleteQRCodeRequest>
{
    public override void Configure()
    {
        Delete("/workspaces/{WorkspaceId}/qrcodes/{Id}");
    }

    public override async Task HandleAsync(DeleteQRCodeRequest req, CancellationToken ct)
    {
        var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);

        var qrCode = await db.QrCodeDesigns
            .Include(q => q.Workspace)
            .FirstOrDefaultAsync(
                q => q.Id == req.Id && q.WorkspaceId == req.WorkspaceId && q.Workspace.OwnerUserId == userId, ct);

        if (qrCode is null)
        {
            await HttpContext.Response.SendAsync(new MessageResponse("QR code not found"), 404, cancellation: ct);
            return;
        }

        db.QrCodeDesigns.Remove(qrCode);
        await db.SaveChangesAsync(ct);

        await HttpContext.Response.SendAsync(new MessageResponse("QR code deleted"), cancellation: ct);
    }
}