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

namespace TrackQrApi.Features.Workspaces.Endpoints;

public class DeleteWorkspaceRequest
{
    public Guid Id { get; set; }
}

public class DeleteWorkspaceEndpoint(AppDbContext db)
    : Endpoint<DeleteWorkspaceRequest>
{
    public override void Configure()
    {
        Delete("/workspaces/{Id}");
    }

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

        var workspace = await db.Workspaces
            .FirstOrDefaultAsync(w => w.Id == req.Id && w.OwnerUserId == userId, ct);

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

        db.Workspaces.Remove(workspace);
        await db.SaveChangesAsync(ct);

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