package com.mosquito.project.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 邮件服务实现
 * 支持mock模式和真实邮件发送模式切换
 */
@Service
public class EmailServiceImpl implements EmailService {

    private static final Logger log = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Value("${app.notification.email.provider:mock}")
    private String emailProvider;

    @Value("${app.notification.email.from: noreply@mosquito.com}")
    private String fromAddress;

    @Value("${app.notification.email.smtp-host:}")
    private String smtpHost;

    @Value("${app.notification.email.smtp-port:587}")
    private int smtpPort;

    @Value("${app.notification.email.username:}")
    private String smtpUsername;

    @Value("${app.notification.email.password:}")
    private String smtpPassword;

    private final Optional<JavaMailSender> mailSender;

    @Autowired
    public EmailServiceImpl(@Autowired(required = false) JavaMailSender mailSender) {
        this.mailSender = Optional.ofNullable(mailSender);
    }

    @Override
    public boolean send(String to, String subject, String content) {
        log.info("[EMAIL] 发送邮件: to={}, subject={}, provider={}", to, subject, emailProvider);

        if ("mock".equalsIgnoreCase(emailProvider)) {
            log.info("[EMAIL-MOCK] 模拟发送邮件: to={}, subject={}", to, subject);
            log.debug("[EMAIL-MOCK] content: {}", content);
            return true;
        }

        // 真实发送模式，需要mailSender
        if (!mailSender.isPresent()) {
            log.error("[EMAIL] 邮件发送失败: 未配置JavaMailSender，请设置app.notification.email.provider=mock或配置SMTP");
            return false;
        }

        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromAddress);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);

            mailSender.get().send(message);
            log.info("[EMAIL] 邮件发送成功: to={}, subject={}", to, subject);
            return true;
        } catch (Exception e) {
            log.error("[EMAIL] 邮件发送失败: to={}, subject={}, error={}", to, subject, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendApprovalTimeoutEmail(String to, String approverName, Long recordId, int progressPercent) {
        String subject = "审批时效预警 - " + progressPercent + "%超时";
        String content = String.format(
            "<html><body>" +
            "<h2>审批时效预警</h2>" +
            "<p>尊敬的 %s：</p>" +
            "<p>您有待处理的审批即将超时（已使用%d%%时间），请尽快处理。</p>" +
            "<p>审批记录ID: %d</p>" +
            "<p>请登录系统及时处理。</p>" +
            "</body></html>",
            approverName, progressPercent, recordId
        );
        return send(to, subject, content);
    }
}
