using System.Runtime.InteropServices;
using PuppeteerSharp.Media;
using PuppeteerSharp;
using Transversal.Interfaces;
using Transversal.Models;

namespace Transversal.Services
{
    public class PuppeteerPdfGeneratorService : IPdfGeneratorService, IAsyncDisposable
    {
        private readonly Browser _browser;
        public PuppeteerPdfGeneratorService()
        {
            string? executablePath = RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
                ? "/usr/bin/chromium"                // Docker/Linux
                : null;                               // Windows local → que use Chrome instalado

            _browser = Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless = true,
                ExecutablePath = executablePath,
                Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }
            }).GetAwaiter().GetResult();
        }
        
        //public PuppeteerPdfGeneratorService()
        //{
        //    // NO USAR BrowserFetcher NUNCA en entorno productivo Docker
        //    _browser = Puppeteer.LaunchAsync(new LaunchOptions
        //    {
        //        Headless = true,
        //        ExecutablePath = "/usr/bin/chromium", // ruta de chromium en la imagen docker
        //        Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }
        //    }).GetAwaiter().GetResult();
        //}
        public async Task<byte[]> GeneratePdfFromHtmlAsync(string htmlContent, PdfGenerationOptions options = null)
        {
            options ??= new PdfGenerationOptions();

            using var page = await _browser.NewPageAsync();
            await page.SetContentAsync(htmlContent);

            var pdfOptions = new PdfOptions
            {
                Format = options.Format,
                Landscape = options.Landscape,
                PrintBackground = options.PrintBackground,
                Scale = options.Scale,
                MarginOptions = options.Margins ?? new MarginOptions(),
                DisplayHeaderFooter = !string.IsNullOrEmpty(options.HeaderTemplate)
                                       || !string.IsNullOrEmpty(options.FooterTemplate),
                HeaderTemplate = options.HeaderTemplate,
                FooterTemplate = options.FooterTemplate
            };

            return await page.PdfDataAsync(pdfOptions);
        }
        public async ValueTask DisposeAsync()
        {
            if (_browser != null)
                await _browser.CloseAsync();
        }
    }
}
