const nodemailer = require('nodemailer')
const config = require('../../config.json')
const path = require('path')
const Logger = require('../../lib/Logger')

const logger = new Logger(path.join(__dirname, '../../logs/Email.log'), 'INFO')

/**
 * 尝试用多个邮箱配置发送邮件
 * @param {string} email - 收件人邮箱
 * @param {string} subject - 邮件主题
 * @param {string} content - 邮件内容（支持 HTML）
 */
async function sendEmail(email, subject, content) {
    return new Promise(async (resolve, reject) => {
        const mail = {
            to: email,
            subject: subject,
            html: content
        }

        // 遍历所有邮箱配置
        for (let i = 0; i < config.email.length; i++) {
            const currentConfig = config.email[i];

            const transporter = nodemailer.createTransport({
                host: currentConfig.host,
                port: currentConfig.port,
                auth: {
                    user: currentConfig.user,
                    pass: currentConfig.password
                }
            })

            mail.from = currentConfig.from

            try {
                await transporter.sendMail(mail)
                logger.info(`邮件发送成功，使用账号: ${currentConfig.user}`)
                return resolve()
            } catch (error) {
                logger.error(`邮件发送失败 (${currentConfig.user})，错误:`, error.stack)
                if (i === config.email.length - 1) {
                    // 最后一个配置也失败了
                    logger.error(`邮件发送失败，所有邮箱配置均不可用`)
                    return
                }
                // 否则继续下一个配置
            }
        }
    })
}

module.exports = sendEmail
