using Fengling.Platform.Infrastructure;
using Microsoft.Extensions.Configuration;
using QRCoder;

namespace Fengling.Console.Services;

public interface IH5LinkService
{
    Task<H5LinkResult> GenerateH5LinkAsync(int tenantId);
}

public class H5LinkResult
{
    public string Link { get; set; } = string.Empty;
    public string QrCodeBase64 { get; set; } = string.Empty;
}

public class H5LinkService : IH5LinkService
{
    private readonly ITenantManager _tenantManager;
    private readonly IConfiguration _configuration;

    public H5LinkService(ITenantManager tenantManager, IConfiguration configuration)
    {
        _tenantManager = tenantManager;
        _configuration = configuration;
    }

    public async Task<H5LinkResult> GenerateH5LinkAsync(int tenantId)
    {
        var tenant = await _tenantManager.FindByIdAsync(tenantId)
            ?? throw new KeyNotFoundException($"Tenant with ID {tenantId} not found");

        var link = GenerateLink(tenant);
        var qrCodeBase64 = GenerateQrCode(link);

        return new H5LinkResult
        {
            Link = link,
            QrCodeBase64 = qrCodeBase64
        };
    }

    private string GenerateLink(Fengling.Platform.Domain.AggregatesModel.TenantAggregate.Tenant tenant)
    {
        var baseUrl = _configuration["AppSettings:DefaultH5BaseUrl"] ?? "https://h5.example.com";
        return $"{baseUrl.TrimEnd('/')}/{tenant.TenantCode}";
    }

    private string GenerateQrCode(string content)
    {
        byte[] qrCodeBytes = PngByteQRCodeHelper.GetQRCode(content, QRCodeGenerator.ECCLevel.M, 20);
        return Convert.ToBase64String(qrCodeBytes);
    }
}
