package com.imprimelibros.erp.common;

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

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

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 username, String resetLink, Locale locale) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom("no-reply@imprimelibros.com");
        helper.setTo(to);
        helper.setSubject(messageSource.getMessage("email.resetPassword.title", null, locale));

        // Variables para la plantilla
        Context context = new Context();
        context.setVariables(Map.of(
                "username", username,
                "resetLink", resetLink,
                "year", String.valueOf(java.time.Year.now().getValue())
        ));

        // Procesar plantilla HTML
        String html = templateEngine.process("email/password-reset", context);
        helper.setText(html, true);

        helper.addInline("companyLogo", new ClassPathResource("static/images/logo-light.png"));

        mailSender.send(message);
    }
}
