package com.ebo.module.utils;

import com.ebo.module.config.EmailConfig;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Properties;

@Slf4j
@Component
public class SendMessageEmail {
    private final EmailConfig emailConfig;

    @Autowired
    public SendMessageEmail(EmailConfig emailConfig) {
        this.emailConfig = emailConfig;
    }
    public void sendAlert(String subject, String message) {
        // 发送邮件
        Properties props = new Properties();
        props.put("mail.smtp.host", emailConfig.getSmtpHost());
        props.put("mail.smtp.port", emailConfig.getSmtpPort());
        props.put("mail.smtp.auth", emailConfig.getSmtpAuth());
        props.put("mail.smtp.ssl.enable", "true");

        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfig.getSmtpUser(), emailConfig.getSmtpPass());
            }
        });

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(emailConfig.getSmtpUser(), false));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailConfig.getToEmail(), false));
            msg.setSubject(subject);
            msg.setText(message);
            msg.setSentDate(new Date());
            Transport.send(msg);
            log.info("Alert sent successfully");
        } catch (MessagingException e) {
            log.info("Failed to send alert", e);
        }
    }
}
