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

public class GetQRCodeEndpoint(AppDbContext db)
    : Endpoint<GetQRCodeRequest, QRCodeResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/qrcodes/{Id}");
    }

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

        var qrCode = await db.QrCodeDesigns
            .Include(q => q.ShortLink)
            .Include(q => q.LogoAsset)
            .Where(q => q.Id == req.Id && q.WorkspaceId == req.WorkspaceId && q.Workspace.OwnerUserId == userId)
            .FirstOrDefaultAsync(ct);

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

        var style = JsonSerializer.Deserialize<QRCodeStyle>(qrCode.StyleJson) ?? new QRCodeStyle();
        var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";

        var response = new QRCodeResponse(
            qrCode.Id,
            qrCode.WorkspaceId,
            qrCode.ProjectId,
            qrCode.ShortLinkId,
            qrCode.ShortLink?.Slug,
            qrCode.Name,
            style,
            qrCode.LogoAssetId,
            qrCode.LogoAsset != null ? $"{baseUrl}/assets/{qrCode.LogoAsset.StorageKey}" : null,
            qrCode.CreatedAt,
            qrCode.UpdatedAt
        );

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