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

namespace TrackQrApi.Features.Links.Endpoints;

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

public class GetLinkEndpoint(AppDbContext db)
    : Endpoint<GetLinkRequest, LinkResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/links/{Id}");
    }

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

        var link = await db.ShortLinks
            .Where(l => l.Id == req.Id && l.WorkspaceId == req.WorkspaceId && l.Workspace.OwnerUserId == userId &&
                        l.DeletedAt == null)
            .Select(l => new LinkResponse(
                l.Id,
                l.WorkspaceId,
                l.ProjectId,
                l.DomainId,
                l.Slug,
                l.DestinationUrl,
                l.Title,
                l.Status.ToString(),
                l.ExpiresAt,
                l.PasswordHash != null,
                l.CreatedAt,
                l.UpdatedAt,
                l.DeletedAt
            ))
            .FirstOrDefaultAsync(ct);

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

        await HttpContext.Response.SendAsync(link, cancellation: ct);
    }
}