const nodemailer = require('nodemailer')
const path = require('path')
const Logger = require('../../lib/Logger')
const { getRuntimeConfig } = require('../../lib/RuntimeConfig')

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
        }

        let emailConfigs = []
        try {
            emailConfigs = await getRuntimeConfig('email', { required: false, defaultValue: [] })
        } catch (error) {
            logger.error(`邮件配置读取失败：${error.stack || error}`)
            return resolve(false)
        }
        if (!Array.isArray(emailConfigs) || emailConfigs.length === 0) {
            logger.error('邮件发送失败：未配置可用邮箱账号')
            return resolve(false)
        }

        // 遍历所有邮箱配置
        for (let i = 0; i < emailConfigs.length; i++) {
            const currentConfig = emailConfigs[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(`${email}邮件发送成功，使用账号: ${currentConfig.user}`)
                return resolve()
            } catch (error) {
                logger.error(`邮件发送失败 (${currentConfig.user})，错误:`, error.stack)
                if (i === emailConfigs.length - 1) {
                    // 最后一个配置也失败了
                    logger.error(`邮件发送失败，所有邮箱配置均不可用`)
                    return resolve(false)
                }
                // 否则继续下一个配置
            }
        }
        return resolve(false)
    })
}

module.exports = sendEmail
