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

namespace TrackQrApi.Features.ApiKeys.Endpoints;

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

public class DeleteApiKeyEndpoint(AppDbContext db)
    : Endpoint<DeleteApiKeyRequest>
{
    public override void Configure()
    {
        Delete("/workspaces/{WorkspaceId}/TrackQrApi-keys/{Id}");
    }

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

        // Verify workspace ownership
        var workspaceExists = await db.Workspaces
            .AnyAsync(w => w.Id == req.WorkspaceId && w.OwnerUserId == userId, ct);

        if (!workspaceExists)
        {
            await HttpContext.Response.SendAsync(new MessageResponse("Workspace not found"), 404, cancellation: ct);
            return;
        }

        var apiKey = await db.ApiKeys
            .FirstOrDefaultAsync(k => k.Id == req.Id && k.WorkspaceId == req.WorkspaceId, ct);

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

        db.ApiKeys.Remove(apiKey);
        await db.SaveChangesAsync(ct);

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