package com.imprimelibros.erp.common.email;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

import org.springframework.context.MessageSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.springframework.core.io.ClassPathResource;

import java.util.Locale;
import java.util.Map;

@Service
public class EmailService {

    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;
    private final MessageSource messageSource;

    public EmailService(JavaMailSender mailSender, TemplateEngine templateEngine, MessageSource messageSource) {
        this.mailSender = mailSender;
        this.templateEngine = templateEngine;
        this.messageSource = messageSource;
    }

    public void sendPasswordResetMail(String to, String fullName, String resetUrl, Locale locale) {
        String subject = messageSource.getMessage("email.resetPassword.title", null, locale);
        Map<String, Object> variables = Map.of(
                "fullName", fullName,
                "resetUrl", resetUrl);
        sendEmail(to, subject, "imprimelibros/email/reset-password", variables, locale);
    }

    public void sendVerificationEmail(String to, String fullName, String verifyUrl, Locale locale) {
        String subject = messageSource.getMessage("email.verify.title", null, locale);
        Map<String, Object> variables = Map.of(
                "fullName", fullName,
                "verifyUrl", verifyUrl,
                "minutes", 60);
        sendEmail(to, subject, "imprimelibros/email/verify", variables, locale);
    }

    // ->>>>>>>> PRIVATE METHODS <<<<<<<<<<<-

    /******************
     * Envía un email usando una plantilla Thymeleaf.
     * 
     * @param to
     * @param subject
     * @param template
     * @param variables
     **********************************************/
    private void sendEmail(String to, String subject, String template, Map<String, Object> variables, Locale locale) {
        try {
            Context ctx = new Context(locale);
            ctx.setVariables(variables);
            ctx.setVariable("subject", subject);
            ctx.setVariable("companyName", "ImprimeLibros");
            ctx.setVariable("year", java.time.Year.now().getValue());

            // Incrusta el CSS (no uses <link> en emails)
            var cssRes = new ClassPathResource("static/assets/css/email.css");
            String emailCss = org.springframework.util.StreamUtils.copyToString(cssRes.getInputStream(),
                    java.nio.charset.StandardCharsets.UTF_8);
            ctx.setVariable("emailCss", emailCss);

            ctx.setVariable("template", template);
            String html = templateEngine.process("imprimelibros/email/layout", ctx);

            MimeMessage msg = mailSender.createMimeMessage();

            MimeMessageHelper h = new MimeMessageHelper(
                    msg,
                    MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                    "UTF-8");

            h.setFrom("no-reply@imprimelibros.com");
            h.setTo(to);
            h.setSubject(subject);

            h.setText(html, true);

            // 3) ahora el inline, con content-type explícito
            ClassPathResource logoRes = new ClassPathResource("static/assets/images/logo-light.png");
            h.addInline("logo", logoRes, "image/png");

            mailSender.send(msg);

        } catch (Exception e) {
            throw new RuntimeException("Error enviando email", e);
        }
    }

}
