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

namespace TrackQrApi.Features.QRCodes.Endpoints;

public class PreviewQRCodeRequest
{
    public Guid WorkspaceId { get; set; }
    public Guid Id { get; set; }
    public int? Size { get; set; }
}

public class PreviewQRCodeEndpoint(
    AppDbContext db,
    IQrCodeGeneratorService qrGenerator,
    IAssetStorageService assetStorage)
    : Endpoint<PreviewQRCodeRequest, QRCodePreviewResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/qrcodes/{Id}/preview");
    }

    public override async Task HandleAsync(PreviewQRCodeRequest 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;
        }

        if (qrCode.ShortLink is null)
        {
            await HttpContext.Response.SendAsync(new MessageResponse("QR code has no associated link"), 400,
                cancellation: ct);
            return;
        }

        var style = JsonSerializer.Deserialize<QRCodeStyle>(qrCode.StyleJson) ?? new QRCodeStyle();
        var size = req.Size ?? 256;

        // Build the short link URL
        // TODO: Use actual domain configuration
        var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";
        var linkUrl = $"{baseUrl}/{qrCode.ShortLink.Slug}";

        // Load logo if available
        Stream? logoStream = null;
        if (qrCode.LogoAsset != null)
        {
            var logoResult = await assetStorage.GetAsync(qrCode.LogoAsset.StorageKey);
            if (logoResult.HasValue) logoStream = logoResult.Value.Stream;
        }

        try
        {
            var dataUrl = qrGenerator.GenerateDataUrl(linkUrl, style, size, logoStream);

            var response = new QRCodePreviewResponse(
                dataUrl,
                "png",
                size,
                size
            );

            await HttpContext.Response.SendAsync(response, cancellation: ct);
        }
        finally
        {
            logoStream?.Dispose();
        }
    }
}