package com.smyhub.store.mengyastorebackendjava.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.net.ssl.SSLSocketFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Properties;
import jakarta.mail.*;
import jakarta.mail.internet.*;

@Slf4j
@Service
public class EmailService {

    private static final DateTimeFormatter FORMATTER =
            DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");

    public void sendOrderNotify(SiteService.SmtpConfig cfg, OrderNotifyData data) {
        if (!cfg.isConfigured() || data.toEmail == null || data.toEmail.isBlank()) {
            return;
        }
        try {
            Properties props = buildMailProperties(cfg);
            Session session = Session.getInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(cfg.email, cfg.password);
                }
            });
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(cfg.email, cfg.fromName, "UTF-8"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(data.toEmail));
            message.setSubject(data.isManual ? "【萌芽小店】您的订单正在处理中" : "【萌芽小店】您的订单已发货");
            message.setContent(buildBody(data), "text/plain; charset=UTF-8");
            Transport.send(message);
            log.info("[Email] 发送成功 order={} to={}", data.orderId, data.toEmail);
        } catch (Exception e) {
            log.error("[Email] 发送失败 order={} to={}: {}", data.orderId, data.toEmail, e.getMessage());
        }
    }

    private Properties buildMailProperties(SiteService.SmtpConfig cfg) {
        Properties props = new Properties();
        props.put("mail.smtp.host", cfg.host);
        props.put("mail.smtp.port", cfg.port);
        props.put("mail.smtp.auth", "true");
        if ("465".equals(cfg.port)) {
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", SSLSocketFactory.class.getName());
            props.put("mail.smtp.socketFactory.fallback", "false");
        } else {
            props.put("mail.smtp.starttls.enable", "true");
        }
        return props;
    }

    private String buildBody(OrderNotifyData data) {
        String now = LocalDateTime.now().format(FORMATTER);
        String recipient = (data.toName != null && !data.toName.isBlank()) ? data.toName : "用户";
        StringBuilder sb = new StringBuilder();
        sb.append("尊敬的 ").append(recipient).append("，\n\n");
        sb.append("    您好！感谢您在萌芽小店的支持与购买。\n\n");
        sb.append("────────────────────────────────\n");
        sb.append("  订单信息\n");
        sb.append("────────────────────────────────\n");
        sb.append("  商品名称：").append(data.productName).append("\n");
        sb.append("  订单编号：").append(data.orderId).append("\n");
        sb.append("  购买数量：").append(data.quantity).append(" 件\n");
        sb.append("  通知时间：").append(now).append("\n");
        sb.append("────────────────────────────────\n\n");
        if (data.isManual) {
            sb.append("  您的订单已成功提交，目前正在等待人工审核与处理。\n");
            sb.append("  工作人员将尽快为您安排发货，请耐心等候。\n");
            sb.append("  发货完成后，我们将另行发送邮件通知。\n\n");
        } else {
            sb.append("  您的订单已完成自动发货，发货内容如下：\n\n");
            if (data.codes != null) {
                for (int i = 0; i < data.codes.size(); i++) {
                    sb.append("  [").append(i + 1).append("] ").append(data.codes.get(i)).append("\n");
                }
                sb.append("\n");
            }
            sb.append("  请妥善保管以上发货内容，切勿泄露给他人。\n\n");
        }
        sb.append("  如有任何疑问，请联系在线客服，我们将竭诚为您服务。\n\n");
        sb.append("────────────────────────────────\n");
        sb.append("  此邮件由系统自动发送，请勿直接回复。\n");
        sb.append("────────────────────────────────\n");
        return sb.toString();
    }

    public static class OrderNotifyData {
        public String toEmail;
        public String toName;
        public String productName;
        public String orderId;
        public int quantity;
        public List<String> codes;
        public boolean isManual;
    }
}
