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

namespace TrackQrApi.Features.Links.Endpoints;

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

public class DeleteLinkEndpoint(AppDbContext db)
    : Endpoint<DeleteLinkRequest>
{
    public override void Configure()
    {
        Delete("/workspaces/{WorkspaceId}/links/{Id}");
    }

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

        var link = await db.ShortLinks
            .Include(l => l.Workspace)
            .FirstOrDefaultAsync(l =>
                l.Id == req.Id &&
                l.WorkspaceId == req.WorkspaceId &&
                l.Workspace.OwnerUserId == userId &&
                l.DeletedAt == null, ct);

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

        // Soft delete
        link.DeletedAt = DateTime.UtcNow;
        await db.SaveChangesAsync(ct);

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