using Documents.Interfaces;
using Documents.Models;
using Domain.Dtos;
using System.Reflection;
using System.Text;
using Transversal.Interfaces;

public class DocumentTemplateService : IDocumentTemplateService
{
    private readonly ITemplateRenderer _templateRenderer;
    private readonly IPdfGeneratorService _pdfGeneratorService;

    public DocumentTemplateService(ITemplateRenderer templateRenderer, IPdfGeneratorService pdfGeneratorService)
    {
        _templateRenderer = templateRenderer;
        _pdfGeneratorService = pdfGeneratorService;
    }

    public async Task<byte[]> GenerateDocumentAsync(DocumentGenerationRequest request)
    {
        // Leer logo
        var logoPath = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "logo.png");
        var logoBase64 = GetImageBase64(logoPath);

        // Inyectar al modelo si corresponde
        if (request.Model is QuoteDto quote)
        {
            quote.LogoBase64 = logoBase64;
        }

        string html = await _templateRenderer.RenderAsync("Quotes/Template_v1.cshtml", request.Model);
        return await _pdfGeneratorService.GeneratePdfFromHtmlAsync(html);
    }

    private static string GetImageBase64(string imagePath)
    {
        if (!File.Exists(imagePath))
            return "";

        byte[] imageBytes = File.ReadAllBytes(imagePath);
        return Convert.ToBase64String(imageBytes);
    }
}


//using Documents.Interfaces;
//using Documents.Models;
//using System.Reflection;
//using System.Text;
//using Transversal.Interfaces;

//namespace Documents.Services
//{
//    public class DocumentTemplateService : IDocumentTemplateService
//    {
//        private readonly ITemplateRenderer _templateRenderer;
//        private readonly IPdfGeneratorService _pdfGeneratorService;

//        public DocumentTemplateService(
//            ITemplateRenderer templateRenderer,
//            IPdfGeneratorService pdfGeneratorService)
//        {
//            _templateRenderer = templateRenderer;
//            _pdfGeneratorService = pdfGeneratorService;
//        }

//        public async Task<byte[]> GenerateDocumentAsync(DocumentGenerationRequest request)
//        {
//            // 👉 Renderizar HTML usando RazorLight
//            string html = await _templateRenderer.RenderAsync("Quotes/Template_v1.cshtml", request.Model);
//            // 👉 Generar PDF desde el HTML
//            return await _pdfGeneratorService.GeneratePdfFromHtmlAsync(html);
//        }
//        private static string GetImageBase64(string imagePath)
//        {
//            if (!File.Exists(imagePath))
//                return "";

//            byte[] imageBytes = File.ReadAllBytes(imagePath);
//            return Convert.ToBase64String(imageBytes);
//        }
//    }
//}
