package service;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


public class EmailService {

    final Properties props = new Properties();
    private final String senderEmail;
    private final String senderPassword;

    public EmailService() {

        try (InputStream input = EmailService.class.getClassLoader().getResourceAsStream("config.properties")) {


            if (input == null) {
                System.err.println("致命错误：在类路径中找不到 config.properties 文件！");
                System.err.println("请确认 'config.properties' 文件已放置在 'src' 文件夹根目录下。");
                throw new RuntimeException("加载配置文件失败: config.properties not found in classpath");
            }

            props.load(input);

        } catch (IOException e) {
            System.err.println("错误：加载 config.properties 文件时发生IO错误！");
            throw new RuntimeException("加载配置文件失败", e);
        }

        this.senderEmail = props.getProperty("mail.sender.email");
        this.senderPassword = props.getProperty("mail.sender.password");
    }


    public void sendVerificationCode(String recipientEmail, String code) throws MessagingException {

        Properties mailProps = new Properties();
        mailProps.put("mail.smtp.host", props.getProperty("smtp.host"));
        mailProps.put("mail.smtp.port", props.getProperty("smtp.port"));
        mailProps.put("mail.smtp.ssl.enable", props.getProperty("smtp.ssl.enable"));
        mailProps.put("mail.smtp.auth", props.getProperty("smtp.auth"));

        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, senderPassword);
            }
        };


        Session session = Session.getInstance(mailProps, authenticator);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(senderEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
        message.setSubject("您的数学学习软件验证码", "UTF-8");


        String content = "<h3>欢迎使用数学学习软件！</h3>" +
                "<p>您的注册验证码是：<b style='color: #007bff; font-size: 18px;'>" + code + "</b></p>" +
                "<p>该验证码5分钟内有效，请勿泄露给他人。</p>";
        message.setContent(content, "text/html; charset=UTF-8");


        Transport.send(message);
        System.out.println("验证码邮件已成功发送至 " + recipientEmail);
    }
}