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 RestoreLinkRequest
{
    public Guid WorkspaceId { get; set; }
    public Guid Id { get; set; }
}

public class RestoreLinkEndpoint(AppDbContext db)
    : Endpoint<RestoreLinkRequest, LinkResponse>
{
    public override void Configure()
    {
        Post("/workspaces/{WorkspaceId}/links/{Id}/restore");
    }

    public override async Task HandleAsync(RestoreLinkRequest 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("Deleted link not found"), 404, cancellation: ct);
            return;
        }

        // Restore the link
        link.DeletedAt = null;
        link.UpdatedAt = DateTime.UtcNow;
        await db.SaveChangesAsync(ct);

        var response = new LinkResponse(
            link.Id,
            link.WorkspaceId,
            link.ProjectId,
            link.DomainId,
            link.Slug,
            link.DestinationUrl,
            link.Title,
            link.Status.ToString(),
            link.ExpiresAt,
            link.PasswordHash != null,
            link.CreatedAt,
            link.UpdatedAt,
            link.DeletedAt
        );

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