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

namespace TrackQrApi.Features.Projects.Endpoints;

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

public class DeleteProjectEndpoint(AppDbContext db)
    : Endpoint<DeleteProjectRequest>
{
    public override void Configure()
    {
        Delete("/workspaces/{WorkspaceId}/projects/{Id}");
    }

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

        var project = await db.Projects
            .Include(p => p.Workspace)
            .FirstOrDefaultAsync(
                p => p.Id == req.Id && p.WorkspaceId == req.WorkspaceId && p.Workspace.OwnerUserId == userId, ct);

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

        db.Projects.Remove(project);
        await db.SaveChangesAsync(ct);

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