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

namespace TrackQrApi.Features.QRCodes.Endpoints;

public class ListQRCodesRequest
{
    public Guid WorkspaceId { get; set; }
    public Guid? ProjectId { get; set; }
    public Guid? ShortLinkId { get; set; }
}

public class ListQRCodesEndpoint(AppDbContext db)
    : Endpoint<ListQRCodesRequest, QRCodeListResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/qrcodes");
    }

    public override async Task HandleAsync(ListQRCodesRequest 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.QrCodeDesigns
            .Where(q => q.WorkspaceId == req.WorkspaceId);

        if (req.ProjectId.HasValue) query = query.Where(q => q.ProjectId == req.ProjectId.Value);

        if (req.ShortLinkId.HasValue) query = query.Where(q => q.ShortLinkId == req.ShortLinkId.Value);

        var qrCodes = await query
            .Include(q => q.ShortLink)
            .Include(q => q.LogoAsset)
            .OrderByDescending(q => q.CreatedAt)
            .ToListAsync(ct);

        var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";

        var response = new QRCodeListResponse(
            qrCodes.Select(q => new QRCodeResponse(
                q.Id,
                q.WorkspaceId,
                q.ProjectId,
                q.ShortLinkId,
                q.ShortLink?.Slug,
                q.Name,
                JsonSerializer.Deserialize<QRCodeStyle>(q.StyleJson) ?? new QRCodeStyle(),
                q.LogoAssetId,
                q.LogoAsset != null ? $"{baseUrl}/assets/{q.LogoAsset.StorageKey}" : null,
                q.CreatedAt,
                q.UpdatedAt
            ))
        );

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