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

namespace TrackQrApi.Features.Assets.Endpoints;

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

public class DeleteAssetEndpoint(AppDbContext db, IAssetStorageService storage)
    : Endpoint<DeleteAssetRequest>
{
    public override void Configure()
    {
        Delete("/workspaces/{WorkspaceId}/assets/{Id}");
    }

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

        var asset = await db.Assets
            .Include(a => a.Workspace)
            .FirstOrDefaultAsync(
                a => a.Id == req.Id && a.WorkspaceId == req.WorkspaceId && a.Workspace.OwnerUserId == userId, ct);

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

        // Check if asset is in use by any QR code
        var inUse = await db.QrCodeDesigns
            .AnyAsync(q => q.LogoAssetId == asset.Id, ct);

        if (inUse)
        {
            await HttpContext.Response.SendAsync(
                new MessageResponse("Cannot delete asset: it is used by one or more QR codes"),
                400,
                cancellation: ct);
            return;
        }

        // Delete from storage
        await storage.DeleteAsync(asset.StorageKey);

        // Delete from database
        db.Assets.Remove(asset);
        await db.SaveChangesAsync(ct);

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