using Fengling.Console.Models.Entities;
using Fengling.Console.Repositories;
using Fengling.Platform.Domain.AggregatesModel.TenantAggregate;
using Microsoft.Extensions.Configuration;
using QRCoder;

namespace Fengling.Console.Services;

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

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

public class H5LinkService : IH5LinkService
{
    private readonly ITenantRepository _tenantRepository;
    private readonly IConfiguration _configuration;

    public H5LinkService(ITenantRepository tenantRepository, IConfiguration configuration)
    {
        _tenantRepository = tenantRepository;
        _configuration = configuration;
    }

    public async Task<H5LinkResult> GenerateH5LinkAsync(long tenantId)
    {
        var tenant = await _tenantRepository.GetByIdAsync(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(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);
    }
}
