/**
 * Email 插件 - 工具函数
 */

const https = require('https')
const http = require('http')
const fs = require('fs')

/**
 * 验证邮箱地址格式
 * @param {string} email - 邮箱地址
 * @returns {boolean}
 */
function isValidEmail(email) {
  if (!email) return false
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

/**
 * 从邮件地址提取显示名称和邮箱
 * @param {string} from - 邮件地址文本
 * @returns {{name: string, email: string}}
 */
function parseEmailAddress(from) {
  if (!from) return { name: '', email: '' }
  
  // 格式: "Display Name <email@example.com>"
  const match = from.match(/^(.+?)\s*<(.+)>$/)
  if (match) {
    return { name: match[1].trim(), email: match[2].trim() }
  }
  
  // 格式: email@example.com
  return { name: '', email: from.trim() }
}

/**
 * 获取环境变量配置
 * @param {Object} args - 参数对象
 * @returns {Object} 合并后的配置
 */
function getConfig(args) {
  return {
    host: args.host || process.env.IMAP_HOST,
    port: args.port || parseInt(process.env.IMAP_PORT) || 993,
    user: args.user || process.env.IMAP_USER,
    password: args.password || process.env.IMAP_PASS
  }
}

/**
 * 从 URL 获取内容
 * @param {string} url - 文件 URL
 * @returns {Promise<Buffer>}
 */
function fetchUrl(url) {
  return new Promise((resolve, reject) => {
    const lib = url.startsWith('https') ? https : http

    const request = lib.get(url, (response) => {
      // 处理重定向
      if (response.statusCode === 301 || response.statusCode === 302) {
        fetchUrl(response.headers.location).then(resolve).catch(reject)
        return
      }

      const chunks = []
      response.on('data', (chunk) => chunks.push(chunk))
      response.on('end', () => resolve(Buffer.concat(chunks)))
      response.on('error', reject)
    })

    request.on('error', reject)
    request.setTimeout(10000, () => {
      request.destroy()
      reject(new Error('下载超时'))
    })
  })
}

/**
 * 处理附件
 * @param {Object} att - 附件定义
 * @returns {Promise<Object>} 处理后的附件
 */
async function processAttachment(att) {
  const attachment = { filename: att.filename }

  if (att.path) {
    // 本地文件
    attachment.content = fs.createReadStream(att.path)
  } else if (att.url) {
    // 远程 URL
    attachment.content = await fetchUrl(att.url)
  } else if (att.content) {
    // Base64 内容
    const base64Data = att.content.replace(/^data:[^;]+;base64,/, '')
    attachment.content = Buffer.from(base64Data, 'base64')
  }

  if (att.cid) {
    attachment.cid = att.cid
  }

  return attachment
}

/**
 * 生成唯一调用 ID
 * @returns {string}
 */
function generateCallId() {
  return `${Date.now()}_${Math.random().toString(36).substr(2, 5)}`
}

module.exports = {
  isValidEmail,
  parseEmailAddress,
  getConfig,
  fetchUrl,
  processAttachment,
  generateCallId
}
