/**
 * IMAP Connector - IMAP邮箱连接器
 * 支持QQ邮箱、Gmail、Outlook等支持IMAP的邮箱服务
 */

const Imap = require('imap');
const { simpleParser } = require('mailparser');
const logger = require('../../../../shared/logger');

class ImapConnector {
  constructor(config) {
    this.config = config;
    this.imap = null;
    this.connected = false;
  }

  /**
   * 连接到邮箱
   */
  async connect() {
    return new Promise((resolve, reject) => {
      this.imap = new Imap({
        user: this.config.user,
        password: this.config.password,
        host: this.config.host,
        port: this.config.port,
        tls: this.config.tls,
        tlsOptions: this.config.tlsOptions || { rejectUnauthorized: false }
      });

      this.imap.once('ready', () => {
        this.connected = true;
        logger.success('IMAP', `已连接到邮箱: ${this.config.user}`);
        resolve();
      });

      this.imap.once('error', (err) => {
        logger.error('IMAP', `连接失败: ${err.message}`);
        reject(err);
      });

      this.imap.once('end', () => {
        this.connected = false;
        logger.info('IMAP', '连接已关闭');
      });

      this.imap.connect();
    });
  }

  /**
   * 断开连接
   */
  disconnect() {
    if (this.imap && this.connected) {
      this.imap.end();
    }
  }

  /**
   * 获取最新的邮件
   * @param {number} count - 获取数量
   * @param {string} folder - 邮箱文件夹名称，默认'INBOX'
   * @returns {Promise<Array>}
   */
  async getLatestEmails(count = 50, folder = 'INBOX') {
    if (!this.connected) {
      await this.connect();
    }

    return new Promise((resolve, reject) => {
      this.imap.openBox(folder, false, (err, box) => {
        if (err) {
          reject(err);
          return;
        }

        // 搜索条件：只搜索未读邮件
        this.imap.search(['UNSEEN'], (err, results) => {
          if (err) {
            reject(err);
            return;
          }

          if (!results || results.length === 0) {
            resolve([]);
            return;
          }

          logger.info('IMAP', `搜索到 ${results.length} 封未读邮件`);

          // 只取最新的N封
          const uids = results.slice(-count);
          const emails = [];
          let processedCount = 0;
          const totalCount = uids.length;

          const fetch = this.imap.fetch(uids, {
            bodies: '',
            markSeen: true
          });

          fetch.on('message', (msg) => {
            msg.on('body', (stream) => {
              simpleParser(stream, (err, parsed) => {
                if (err) {
                  logger.warn('IMAP', `解析邮件失败: ${err.message}`);
                } else {
                  emails.push({
                    uid: msg.uid,
                    from: parsed.from?.text || '',
                    to: parsed.to?.text || '',
                    subject: parsed.subject || '',
                    date: parsed.date,
                    text: parsed.text || '',
                    html: parsed.html || '',
                    headers: parsed.headers
                  });
                }
                
                processedCount++;
                // 所有邮件都处理完后才resolve
                if (processedCount === totalCount) {
                  logger.info('IMAP', `成功解析 ${emails.length} 封邮件`);
                  resolve(emails);
                }
              });
            });
          });

          fetch.once('error', (err) => {
            reject(err);
          });
        });
      });
    });
  }

  /**
   * 搜索包含特定关键词的邮件
   * @param {string} subject - 主题关键词
   * @param {number} sinceDays - 几天内
   * @returns {Promise<Array>}
   */
  async searchBySubject(subject, sinceDays = 1) {
    if (!this.connected) {
      await this.connect();
    }

    return new Promise((resolve, reject) => {
      this.imap.openBox('INBOX', false, (err, box) => {
        if (err) {
          reject(err);
          return;
        }

        const sinceDate = new Date();
        sinceDate.setDate(sinceDate.getDate() - sinceDays);

        this.imap.search([['SINCE', sinceDate], ['SUBJECT', subject]], (err, results) => {
          if (err) {
            reject(err);
            return;
          }

          if (!results || results.length === 0) {
            resolve([]);
            return;
          }

          const emails = [];
          const fetch = this.imap.fetch(results, {
            bodies: '',
            markSeen: true
          });

          fetch.on('message', (msg) => {
            msg.on('body', (stream) => {
              simpleParser(stream, (err, parsed) => {
                if (err) {
                  logger.warn('IMAP', `解析邮件失败: ${err.message}`);
                  return;
                }

                emails.push({
                  uid: msg.uid,
                  from: parsed.from?.text || '',
                  to: parsed.to?.text || '',
                  subject: parsed.subject || '',
                  date: parsed.date,
                  text: parsed.text || '',
                  html: parsed.html || '',
                  headers: parsed.headers
                });
              });
            });
          });

          fetch.once('error', (err) => {
            reject(err);
          });

          fetch.once('end', () => {
            resolve(emails);
          });
        });
      });
    });
  }

  /**
   * 标记邮件为已读
   * @param {number} uid - 邮件UID
   */
  async markAsRead(uid) {
    if (!this.connected) {
      return;
    }

    return new Promise((resolve, reject) => {
      this.imap.addFlags(uid, ['\\Seen'], (err) => {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }
}

module.exports = ImapConnector;
