package com.ebo.module.utils;

import com.ebo.module.config.QQEmailConfig;
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 QQEmailConfig qqemailConfig;

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

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

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(qqemailConfig.getSmtpUser(), false));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(qqemailConfig.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);
        }
    }
}
