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 ExportQRCodeRequest
{
    public Guid WorkspaceId { get; set; }
    public Guid Id { get; set; }
    public string? Format { get; set; } // png or svg
    public int? Size { get; set; }
}

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

    public override async Task HandleAsync(ExportQRCodeRequest 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 format = (req.Format ?? "png").ToLowerInvariant();
        var size = req.Size ?? 512;

        // Build the short link URL with QR tracking param
        var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}";
        var linkUrl = $"{baseUrl}/{qrCode.ShortLink.Slug}?qr={qrCode.Id}";

        var filename = $"qrcode-{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
        {
            if (format == "svg")
            {
                // SVG doesn't support logo overlay currently
                var svg = qrGenerator.GenerateSvg(linkUrl, style, size);
                HttpContext.Response.ContentType = "image/svg+xml";
                HttpContext.Response.Headers.ContentDisposition = $"attachment; filename=\"{filename}.svg\"";
                await HttpContext.Response.WriteAsync(svg, ct);
            }
            else
            {
                var png = qrGenerator.GeneratePng(linkUrl, style, size, logoStream);
                HttpContext.Response.ContentType = "image/png";
                HttpContext.Response.Headers.ContentDisposition = $"attachment; filename=\"{filename}.png\"";
                await HttpContext.Response.Body.WriteAsync(png, ct);
            }
        }
        finally
        {
            logoStream?.Dispose();
        }
    }
}