package com.bizzan.bitrade.vendor.provider.support;

import com.bizzan.bitrade.service.SysConfigService;
import com.bizzan.bitrade.util.ThreadUtil;
import com.bizzan.bitrade.util.Callback;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
@Slf4j
public class EmailProvider {

    /** AWS SES 已验证的发件人地址 */
    @Value("${aws.ses.from:}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private SysConfigService sysConfigService;

    /** 异步发送，失败只打日志不抛出 */
    public void sendSingleSendMail(String to, String subject, String htmlBody) {
        ThreadUtil.executeInThread(new Callback() {
            @Override
            public void execute(Object obj) {
                try {
                    sendHtmlMailSync(to, subject, htmlBody);
                } catch (Exception e) {
                    log.error("[SES-SMTP] async send failed to={}, subject={}, msg={}", to, subject, e.getMessage());
                }
            }
        });
    }

    /** 同步发送，异常向上抛出 */
    public void sendSingleSendMailSync(String to, String subject, String htmlBody) throws MessagingException {
        sendHtmlMailSync(to, subject, htmlBody);
    }

    /** HTML 邮件（异常吞掉，只打日志） */
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        try {
            sendHtmlMailSync(to, subject, content);
        } catch (Exception e) {
            log.error("[SES-SMTP] sendHtmlMail failed to={}, subject={}, msg={}", to, subject, e.getMessage());
        }
    }

    /** HTML 邮件（同步，异常向上传播） */
    public void sendHtmlMailSync(String to, String subject, String content) throws MessagingException {
        String fromAlias = buildFromAddress();
        log.info("[SES-SMTP] sending email from={} to={} subject={}", fromAlias, to, subject);
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(fromAlias);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            javaMailSender.send(message);
            log.info("[SES-SMTP] email sent successfully to={}", to);
        } catch (MessagingException e) {
            log.error("[SES-SMTP] send email failed to={}, msg={}", to, e.getMessage());
            throw e;
        }
    }

    /**
     * 构造带显示名称的发件人地址，如 "IBit <noreply@example.com>"
     */
    private String buildFromAddress() {
        try {
            String projectName = sysConfigService.get().getProjectName();
            if (projectName != null && !projectName.isEmpty()) {
                return projectName + " <" + from + ">";
            }
        } catch (Exception e) {
            log.warn("[SES-SMTP] failed to get project name, using plain from address");
        }
        return from;
    }
}
