/**
 * 邮件发送服务
 * 使用 nodemailer + SMTP 发送真实邮件
 * 配置在 .env 中: SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, ALERT_EMAIL
 */

const nodemailer = require('nodemailer');

/**
 * 获取邮件发送器（单例）
 */
let transporter = null;
function getTransporter() {
  if (transporter) return transporter;
  
  const host = process.env.SMTP_HOST || 'smtp.163.com';
  const port = parseInt(process.env.SMTP_PORT) || 465;
  const user = process.env.SMTP_USER;
  const pass = process.env.SMTP_PASS;

  if (!user || !pass) {
    console.warn('[邮件] SMTP未配置，邮件将使用模拟模式');
    return null;
  }

  transporter = nodemailer.createTransport({
    host,
    port,
    secure: port === 465,
    auth: { user, pass },
  });

  return transporter;
}

/**
 * 发送邮件
 * @param {string} to       收件邮箱
 * @param {string} subject  邮件主题
 * @param {string} content  邮件正文（纯文本/HTML）
 * @param {object} options  { isHtml?: boolean }
 * @returns {Promise<{success: boolean, messageId?: string, error?: string}>}
 */
async function send(to, subject, content, options = {}) {
  const t = getTransporter();

  if (!t) {
    // 模拟模式
    console.log(`[邮件模拟] 发送到 ${to}`);
    console.log(`[邮件模拟] 主题: ${subject}`);
    return { success: true, messageId: `EML_${Date.now()}`, error: null };
  }

  try {
    const from = process.env.SMTP_USER;
    const info = await t.sendMail({
      from: `"省胜优铺" <${from}>`,
      to,
      subject,
      text: options.isHtml ? undefined : content,
      html: options.isHtml ? content : undefined,
    });
    console.log(`[邮件] 已发送到 ${to}, messageId=${info.messageId}`);
    return { success: true, messageId: info.messageId };
  } catch (err) {
    console.error('[邮件] 发送失败:', err.message);
    return { success: false, error: err.message };
  }
}

/**
 * 发送安全告警邮件（破解/篡改通知）
 * @param {object} alertInfo { type, detail, serverInfo }
 */
async function sendAlert(alertInfo) {
  const to = process.env.ALERT_EMAIL || 'dsjt77@163.com';
  const now = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
  const subject = `【安全告警】省胜优铺系统异常 - ${alertInfo.type}`;

  const content = `
══════ 安全告警 ══════
时间：${now}
类型：${alertInfo.type}
详情：${alertInfo.detail}

服务器信息：
  - 主机名: ${alertInfo.serverInfo?.hostname || 'N/A'}
  - 系统ID: ${alertInfo.serverInfo?.systemId || 'N/A'}
  - 域名: ${alertInfo.serverInfo?.domain || 'N/A'}
  - IP: ${alertInfo.serverInfo?.ip || 'N/A'}
  - 节点名: ${alertInfo.serverInfo?.node || 'N/A'}
  - 平台: ${alertInfo.serverInfo?.platform || 'N/A'}

━━━━ 建议操作 ━━━━
1. 登录后台检查系统完整性
2. 确认是否为正常开发操作
3. 如确认被破解，保留证据并启动维权流程
  `;

  return send(to, subject, content);
}

module.exports = { send, sendAlert };
