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

namespace TrackQrApi.Features.Links.Endpoints;

public class ListLinksRequest
{
    public Guid WorkspaceId { get; set; }
    public Guid? ProjectId { get; set; }
    public string? Status { get; set; }
    public bool IncludeDeleted { get; set; } = false;
}

public class ListLinksEndpoint(AppDbContext db)
    : Endpoint<ListLinksRequest, LinkListResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/links");
    }

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

        // Verify workspace ownership
        var workspaceExists = await db.Workspaces
            .AnyAsync(w => w.Id == req.WorkspaceId && w.OwnerUserId == userId, ct);

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

        var query = db.ShortLinks
            .Where(l => l.WorkspaceId == req.WorkspaceId);

        // Filter by deleted status (exclude soft-deleted by default)
        if (!req.IncludeDeleted) query = query.Where(l => l.DeletedAt == null);

        // Filter by project if specified
        if (req.ProjectId.HasValue) query = query.Where(l => l.ProjectId == req.ProjectId.Value);

        // Filter by status if specified
        if (!string.IsNullOrEmpty(req.Status) && Enum.TryParse<ShortLinkStatus>(req.Status, true, out var status))
            query = query.Where(l => l.Status == status);

        var links = await query
            .OrderByDescending(l => l.CreatedAt)
            .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
            ))
            .ToListAsync(ct);

        await HttpContext.Response.SendAsync(new LinkListResponse(links), cancellation: ct);
    }
}