import { simpleParser } from 'mailparser';
import type { ParsedMail } from 'mailparser';
import Imap from 'imap';

export type { ParsedMail };

export interface EmailCredentials {
  user: string;
  password: string;
  host: string;
  port: number;
  tls: boolean;
}

export async function parseEmail(emailContent: string): Promise<ParsedMail> {
  return await simpleParser(emailContent);
}

export function getIMAPConnection(credentials: EmailCredentials): Promise<any> {
  return new Promise((resolve, reject) => {
    const imap = new Imap({
      user: credentials.user,
      password: credentials.password,
      host: credentials.host,
      port: credentials.port,
      tls: credentials.tls,
      tlsOptions: { rejectUnauthorized: false }
    });

    imap.once('ready', () => {
      console.log('[IMAP] Connection ready');
      resolve(imap);
    });

    imap.once('error', (err: Error) => {
      console.error('[IMAP] Connection error:', err);
      reject(err);
    });

    imap.connect();
  });
}

export function searchEmails(imap: any, criteria: any[]): Promise<number[]> {
  return new Promise((resolve, reject) => {
    imap.search(criteria, (err: Error | null, results: number[]) => {
      if (err) reject(err);
      else resolve(results || []);
    });
  });
}

export function fetchEmail(imap: any, msgId: number, options: any): Promise<string> {
  return new Promise((resolve, reject) => {
    let emailData = '';
    
    const fetch = imap.fetch(msgId, options);
    
    fetch.on('message', (msg: any) => {
      msg.on('body', (stream: any) => {
        stream.on('data', (chunk: Buffer) => {
          emailData += chunk.toString();
        });
        
        stream.once('end', () => {
          resolve(emailData);
        });
      });
    });
    
    fetch.once('error', (err: Error) => {
      reject(err);
    });
    
    fetch.once('end', () => {
      if (!emailData) {
        reject(new Error('No email data received'));
      }
    });
  });
}
