/**
 * Email 插件 - 邮件解析器
 */

const { simpleParser } = require('mailparser')

/**
 * 解析邮件内容
 * @param {Stream} stream - 邮件流
 * @returns {Promise<Object>} 解析后的邮件对象
 */
async function parseEmail(stream) {
  return await simpleParser(stream)
}

/**
 * 将邮件对象标准化
 * @param {Object} mail - mailparser 解析结果
 * @param {number} defaultUid - 默认 UID
 * @returns {Object} 标准化的邮件对象
 */
function normalizeEmail(mail, defaultUid) {
  return {
    uid: mail.uid || defaultUid,
    messageId: mail.messageId,
    subject: mail.subject,
    from: mail.from?.text || '',
    fromName: mail.from?.value?.[0]?.name || '',
    fromAddress: mail.from?.value?.[0]?.address || '',
    to: mail.to?.text || '',
    toName: mail.to?.value?.[0]?.name || '',
    toAddress: mail.to?.value?.[0]?.address || '',
    date: mail.date?.toISOString() || '',
    text: mail.text || mail.textAsHtml || '',
    html: mail.html,
    attachments: parseAttachments(mail.attachments),
    headers: parseHeaders(mail.headers)
  }
}

/**
 * 解析附件列表
 * @param {Array} attachments - 附件数组
 * @returns {Array} 标准化的附件列表
 */
function parseAttachments(attachments) {
  if (!attachments || !Array.isArray(attachments)) {
    return []
  }

  return attachments.map(att => ({
    filename: att.filename,
    contentType: att.contentType,
    contentId: att.contentId,
    size: att.size,
    headers: att.headers
  }))
}

/**
 * 解析邮件头
 * @param {Map|Object} headers - 邮件头
 * @returns {Object} 标准化的头信息
 */
function parseHeaders(headers) {
  if (!headers) return {}

  const result = {}
  if (headers instanceof Map) {
    for (const [key, value] of headers) {
      result[key.toLowerCase()] = Array.isArray(value) ? value.join(', ') : value
    }
  } else {
    for (const [key, value] of Object.entries(headers)) {
      result[key.toLowerCase()] = Array.isArray(value) ? value.join(', ') : value
    }
  }

  return result
}

/**
 * 检测邮件编码
 * @param {string} charset - 字符集
 * @returns {string} 标准化的字符集名称
 */
function normalizeCharset(charset) {
  if (!charset) return 'utf-8'

  const charsetMap = {
    'gb2312': 'gb18030',
    'gbk': 'gb18030',
    'windows-1252': 'cp1252'
  }

  return charsetMap[charset.toLowerCase()] || charset.toLowerCase()
}

/**
 * 清理邮件文本内容
 * @param {string} text - 原始文本
 * @returns {string} 清理后的文本
 */
function cleanText(text) {
  if (!text) return ''

  return text
    .replace(/\r\n/g, '\n')  // 统一换行符
    .replace(/\t/g, ' ')     // Tab 转为空格
    .replace(/ +/g, ' ')     // 多个空格合并为一个
    .replace(/\n{3,}/g, '\n\n')  // 超过两个连续换行合并为两个
    .trim()
}

/**
 * 从文本中提取邮箱地址
 * @param {string} text - 文本内容
 * @returns {Array<string>} 邮箱地址列表
 */
function extractEmails(text) {
  if (!text) return []

  const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g
  const matches = text.match(emailRegex) || []

  // 去重
  return [...new Set(matches)]
}

module.exports = {
  parseEmail,
  normalizeEmail,
  parseAttachments,
  parseHeaders,
  normalizeCharset,
  cleanText,
  extractEmails
}
