/**
 * IMAP邮箱提供商
 * 100%保持旧框架的逻辑不变
 */

import Imap = require('imap');
import { simpleParser } from 'mailparser';
import { IEmailProvider, EmailMessage, EmailProviderConfig } from './IEmailProvider';

export class ImapEmailProvider implements IEmailProvider {
  private config: EmailProviderConfig;
  private imap: any = null;
  private connected: boolean = false;
  
  constructor(config: EmailProviderConfig) {
    this.config = config;
  }
  
  /**
   * 连接到邮箱
   */
  async connect(): Promise<void> {
    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;
        console.log(`[IMAP] 已连接到邮箱: ${this.config.user}`);
        resolve();
      });
      
      this.imap.once('error', (err: Error) => {
        console.error(`[IMAP] 连接失败: ${err.message}`);
        reject(err);
      });
      
      this.imap.once('end', () => {
        this.connected = false;
        console.log('[IMAP] 连接已关闭');
      });
      
      this.imap.connect();
    });
  }
  
  /**
   * 断开连接
   */
  disconnect(): void {
    if (this.imap && this.connected) {
      this.imap.end();
    }
  }
  
  /**
   * 获取最新的邮件（与旧框架逻辑完全一致）
   */
  async getLatestEmails(count: number = 50, folder: string = 'INBOX'): Promise<EmailMessage[]> {
    if (!this.connected) {
      await this.connect();
    }
    
    return new Promise((resolve, reject) => {
      this.imap.openBox(folder, false, (err: Error, box: any) => {
        if (err) {
          reject(err);
          return;
        }
        
        // 搜索条件：只搜索未读邮件
        this.imap.search(['UNSEEN'], (err: Error, results: number[]) => {
          if (err) {
            reject(err);
            return;
          }
          
          if (!results || results.length === 0) {
            resolve([]);
            return;
          }
          
          console.log(`[IMAP] 搜索到 ${results.length} 封未读邮件`);
          
          // 只取最新的N封
          const uids = results.slice(-count);
          const emails: EmailMessage[] = [];
          let processedCount = 0;
          const totalCount = uids.length;
          
          const fetch = this.imap.fetch(uids, {
            bodies: '',
            markSeen: true
          });
          
          fetch.on('message', (msg: any) => {
            msg.on('body', (stream: any) => {
              simpleParser(stream, (err: Error | null, parsed: any) => {
                if (err) {
                  console.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) {
                  console.log(`[IMAP] 成功解析 ${emails.length} 封邮件`);
                  resolve(emails);
                }
              });
            });
          });
          
          fetch.once('error', (err: Error) => {
            reject(err);
          });
        });
      });
    });
  }
  
  /**
   * 搜索包含特定关键词的邮件（与旧框架逻辑完全一致）
   */
  async searchBySubject(subject: string, sinceDays: number = 1): Promise<EmailMessage[]> {
    if (!this.connected) {
      await this.connect();
    }
    
    return new Promise((resolve, reject) => {
      this.imap.openBox('INBOX', false, (err: Error, box: any) => {
        if (err) {
          reject(err);
          return;
        }
        
        const sinceDate = new Date();
        sinceDate.setDate(sinceDate.getDate() - sinceDays);
        
        this.imap.search([['SINCE', sinceDate], ['SUBJECT', subject]], (err: Error, results: number[]) => {
          if (err) {
            reject(err);
            return;
          }
          
          if (!results || results.length === 0) {
            resolve([]);
            return;
          }
          
          const emails: EmailMessage[] = [];
          const fetch = this.imap.fetch(results, {
            bodies: '',
            markSeen: true
          });
          
          fetch.on('message', (msg: any) => {
            msg.on('body', (stream: any) => {
              simpleParser(stream, (err: Error | null, parsed: any) => {
                if (err) {
                  console.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: Error) => {
            reject(err);
          });
          
          fetch.once('end', () => {
            resolve(emails);
          });
        });
      });
    });
  }
  
  /**
   * 标记邮件为已读
   */
  async markAsRead(uid: number): Promise<void> {
    if (!this.connected) {
      return;
    }
    
    return new Promise((resolve, reject) => {
      this.imap.addFlags(uid, ['\\Seen'], (err: Error) => {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }
}
