package com.imprimelibros.erp;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Year;
import java.util.Locale;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.springframework.boot.test.context.SpringBootTest;

import com.imprimelibros.erp.common.email.EmailService;

@SpringBootTest
public class verificationEmailTest {

    @Autowired
    private EmailService emailService;


    private SpringTemplateEngine buildEngineForTests() {
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix("templates/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding("UTF-8");
        resolver.setCacheable(false);

        // MessageSource para tests (apunta a tus ficheros de la carpeta i18n)
        ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
        ms.setBasenames(
                "i18n/app",
                "i18n/auth",
                "i18n/email", // <-- imprescindible para las claves email.*
                "i18n/login",
                "i18n/margenesPresupuesto",
                "i18n/presupuesto",
                "i18n/users",
                "i18n/validation");
        ms.setDefaultEncoding("UTF-8");
        ms.setFallbackToSystemLocale(false);

        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(resolver);
        engine.setTemplateEngineMessageSource(ms); // <-- clave

        return engine;
    }

    private String readClasspath(String path) throws Exception {
        ClassPathResource res = new ClassPathResource(path);
        return StreamUtils.copyToString(res.getInputStream(), StandardCharsets.UTF_8);
    }

    @Test
    void render_verify_email_should_include_content_and_white_card() throws Exception {
        SpringTemplateEngine engine = buildEngineForTests();

        Locale locale = Locale.forLanguageTag("es-ES");
        Context ctx = new Context(locale);
        String verifyUrl = "https://imprimelibros.com/verify?token=TESTTOKEN";
        ctx.setVariable("subject", "Verifica tu correo");
        ctx.setVariable("companyName", "ImprimeLibros");
        ctx.setVariable("year", Year.now().getValue());
        ctx.setVariable("fullName", "Juan Pérez");
        ctx.setVariable("verifyUrl", verifyUrl);
        ctx.setVariable("minutes", 60);

        // CSS embebido para el test (si lo usas)
        String emailCss = readClasspath("static/assets/css/email.css");
        ctx.setVariable("emailCss", emailCss);

        // === Render ===
        String html = engine.process("imprimelibros/email/verify", ctx);

        // Vuelca siempre el HTML para inspección
        File outDir = new File("target/email-test");
        outDir.mkdirs();
        File out = new File(outDir, "verify.html");
        try (FileOutputStream fos = new FileOutputStream(out)) {
            fos.write(html.getBytes(StandardCharsets.UTF_8));
        }
        System.out.println("📧 HTML generado en: " + out.getAbsolutePath());

        // === Asserts robustos (sin depender de traducciones) ===

        // 1) El slot se ha reemplazado (aparece la celda y hay contenido dentro)
        assertThat(html)
                .as("Debe existir la celda del contenido")
                .contains("<td class=\"email-content\"");
        assertThat(html.replaceAll("\\s+", " "))
                .as("El fragmento debe inyectar párrafos dentro del slot")
                .containsPattern("<td class=\\\"email-content\\\"[^>]*>.*?<p>.*?</p>.*?</td>");

        // 2) Debe aparecer la URL del botón de verificación
        assertThat(html).as("El verifyUrl debe estar inyectado").contains(verifyUrl);

        // 3) Debe existir un enlace con clase 'btn' (el botón)
        assertThat(html).as("Debe existir el botón con clase .btn").contains("<a ", "class=\"btn");

        // 4) Fondos (wrapper gris claro y tarjeta blanca) con bgcolor y/o inline
        assertThat(html).as("Wrapper debe tener fondo claro").contains("bgcolor=\"#f5f7fb\"");
        assertThat(html).as("Tarjeta debe tener fondo blanco").contains("bgcolor=\"#ffffff\"");

        // 5) Logo inline presente
        assertThat(html).as("Logo CID debe estar").contains("cid:logo");

        assertThat(html).doesNotContain("??email."); // sin claves sin resolver
    }

    @Test
    void send_verification_email_live() {
        // Lee el destinatario del entorno para no hardcodearlo ni spamear
        String to = System.getenv().getOrDefault("MAIL_TO", "jaimejimenezortega@gmail.com");
        String verifyUrl = "https://imprimelibros.com/verify?token=LIVE_TEST";
        Locale locale = Locale.forLanguageTag("es-ES");

        // Si no lanza excepción, damos el test por OK
        emailService.sendVerificationEmail(to, "Usuario", verifyUrl, locale);
    }

}
