/**
 * Email Verification Service
 * 邮箱验证码服务 - 统一入口
 */

const ImapConnector = require('./connectors/imap-connector');
const WindsurfParser = require('./parsers/windsurf-parser');
const emailConfig = require('./email-config');
const logger = require('../../../shared/logger');

class EmailVerificationService {
  constructor(config = null) {
    this.config = config || emailConfig.primary;
    this.connector = null;
    this.parsers = [
      new WindsurfParser()
      // 未来添加更多解析器
      // new GitHubParser(),
      // new TwitterParser(),
    ];
  }

  /**
   * 获取验证码
   * @param {string} siteName - 网站名称（如 'windsurf'）
   * @param {string} recipientEmail - 接收验证码的邮箱地址
   * @param {number} timeout - 超时时间（秒）
   * @returns {Promise<string>} - 验证码
   */
  async getVerificationCode(siteName, recipientEmail, timeout = 120) {
    logger.info('EmailVerification', `开始获取 ${siteName} 的验证码...`);
    logger.info('EmailVerification', `接收邮箱: ${recipientEmail}`);

    return new Promise((resolve, reject) => {
      const startTime = Date.now();
      const maxWaitTime = timeout * 1000;
      
      // 创建IMAP连接
      this.connector = new ImapConnector(this.config);
      
      let checkInterval;
      let isResolved = false;

      const checkMail = async () => {
        if (Date.now() - startTime > maxWaitTime) {
          clearInterval(checkInterval);
          this.connector.disconnect();
          if (!isResolved) {
            isResolved = true;
            reject(new Error('获取验证码超时'));
          }
          return;
        }

        try {
          // 获取最新邮件
          logger.info('EmailVerification', '正在搜索邮件...');
          const emails = await this.connector.getLatestEmails(50, 'INBOX');
          
          if (!emails || emails.length === 0) {
            logger.info('EmailVerification', '暂无未读邮件');
            return;
          }
          
          logger.info('EmailVerification', `✓ 找到 ${emails.length} 封未读邮件`);
          
          // 按日期倒序排序（最新的在前）
          emails.sort((a, b) => {
            const dateA = a.date ? new Date(a.date).getTime() : 0;
            const dateB = b.date ? new Date(b.date).getTime() : 0;
            return dateB - dateA;
          });
          
          // 打印最近5条邮件信息
          const recentEmails = emails.slice(0, 5);
          logger.info('EmailVerification', '='.repeat(60));
          logger.info('EmailVerification', '最近5条邮件：');
          recentEmails.forEach((email, index) => {
            const dateStr = email.date ? new Date(email.date).toLocaleString('zh-CN') : 'N/A';
            logger.info('EmailVerification', `  ${index + 1}. 时间: ${dateStr}`);
            logger.info('EmailVerification', `     发件人: ${email.from}`);
            logger.info('EmailVerification', `     主题: ${email.subject}`);
            logger.info('EmailVerification', `     收件人: ${email.to}`);
          });
          logger.info('EmailVerification', '='.repeat(60));
          
          // 查找匹配的邮件并提取验证码
          // 必须检查收件人是否匹配，避免获取到旧邮件的验证码
          for (const email of emails) {
            if (isResolved) return;
            
            logger.info('EmailVerification', `检查邮件: 发件人="${email.from}", 主题="${email.subject}", 收件人="${email.to}", 时间="${email.date}"`);
            
            // 提取收件人邮箱地址（可能包含名字，如 "Name <email@example.com>"）
            const emailToMatch = email.to.match(/<(.+?)>/);
            const actualRecipient = emailToMatch ? emailToMatch[1] : email.to;
            
            // 检查收件人是否匹配
            if (!actualRecipient.includes(recipientEmail)) {
              logger.info('EmailVerification', `  ✗ 跳过：收件人不匹配（期望：${recipientEmail}，实际：${actualRecipient}）`);
              continue;
            }
            logger.success('EmailVerification', `  ✓ 收件人匹配！`);
            
            for (const parser of this.parsers) {
              if (parser.canParse(email)) {
                logger.success('EmailVerification', `  ✓ 找到匹配的邮件: ${email.subject}`);
                
                const code = parser.extractCode(email);
                if (code) {
                  clearInterval(checkInterval);
                  this.connector.disconnect();
                  if (!isResolved) {
                    isResolved = true;
                    logger.success('EmailVerification', `  ✓ 成功提取验证码: ${code}`);
                    resolve(code);
                  }
                  return;
                } else {
                  logger.warn('EmailVerification', `  邮件匹配但无法提取验证码`);
                }
              }
            }
          }
          
          logger.warn('EmailVerification', `未找到匹配的验证码邮件`);
          
        } catch (err) {
          logger.error('EmailVerification', `检查邮件失败: ${err.message}`);
        }
      };

      // 连接成功后开始检查
      this.connector.connect().then(() => {
        logger.success('EmailVerification', 'IMAP连接成功，开始监听验证码邮件...');
        checkMail();
        checkInterval = setInterval(checkMail, emailConfig.search.checkInterval * 1000);
      }).catch((err) => {
        if (!isResolved) {
          isResolved = true;
          reject(new Error(`IMAP连接失败: ${err.message}`));
        }
      });
    });
  }

  /**
   * 搜索特定主题的邮件并提取验证码
   * @param {string} subject - 邮件主题关键词
   * @param {number} timeout - 超时时间（秒）
   * @returns {Promise<string>}
   */
  async getCodeBySubject(subject, timeout = 60) {
    logger.info('EmailVerification', `搜索主题包含 "${subject}" 的邮件...`);

    try {
      this.connector = new ImapConnector(this.config);
      await this.connector.connect();

      const startTime = Date.now();
      const checkInterval = emailConfig.search.checkInterval * 1000;

      while (Date.now() - startTime < timeout * 1000) {
        const emails = await this.connector.searchBySubject(subject, 1);

        if (emails && emails.length > 0) {
          for (const email of emails.reverse()) {
            for (const parser of this.parsers) {
              if (parser.canParse(email)) {
                const code = parser.extractCode(email);
                if (code) {
                  logger.success('EmailVerification', `提取到验证码: ${code}`);
                  this.connector.disconnect();
                  return code;
                }
              }
            }
          }
        }

        await this.sleep(checkInterval);
      }

      this.connector.disconnect();
      throw new Error(`获取验证码超时`);

    } catch (error) {
      if (this.connector) {
        this.connector.disconnect();
      }
      throw error;
    }
  }

  /**
   * 添加新的解析器
   * @param {BaseParser} parser - 解析器实例
   */
  addParser(parser) {
    this.parsers.push(parser);
  }

  /**
   * 休眠
   * @param {number} ms - 毫秒
   */
  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

module.exports = EmailVerificationService;
