import { ImapFlow } from 'imapflow'

interface ImapConfig {
    user: string;
    password: string;
    host: string;
    port: number;
    tls: boolean;
}

async function getMessagesFromInboxWithFilter(imapConfig: ImapConfig, fromAddress: string, toAddress: string): Promise<void> {
    const client = new ImapFlow({
        host: imapConfig.host,
        port: imapConfig.port,
        secure: imapConfig.tls,
        auth: {
            user: imapConfig.user,
            pass: imapConfig.password
        }
    });

    try {
        // Connect to the IMAP server
        await client.connect();

        // Select and lock the INBOX
        let lock = await client.getMailboxLock('INBOX');

        try {
            // Search for messages where the 'from' address and 'to' address match the specified filters
            const searchCriteria = {
                from: fromAddress,
                to: toAddress
            };

            // Search for messages matching the criteria
            const messages = client.fetch({ from: fromAddress, to: toAddress }, { envelope: true, source: true });

            // Iterate through each filtered message and print details
            for await (let message of messages) {
                console.log('Message ID:', message.uid);
                console.log('From:', message.envelope?.from?.map(f => `${f.name} <${f.address}>`).join(', '));
                console.log('To:', message.envelope?.to?.map(f => `${f.name} <${f.address}>`).join(', '));
                console.log('Subject:', message.envelope?.subject);
                console.log('Date:', message.envelope?.date);

                // If you need the message body, you can access it from message.source
                console.log('Raw message source:', message.source.toString());
            }
        } finally {
            // Always release the lock
            lock.release();
        }

        // Log out and close the connection
        await client.logout();

    } catch (err) {
        console.error('Error fetching messages:', err);
        throw err;
    }
}

// Configuration for IMAP
const imapConfig = {
  host: 'imap.example.com',
  port: 993,
  auth: {
    user: 'your_email@example.com',
    pass: 'your_password'
  },
  secure: true
};

// Create a draft email
export const draft = async (subject: string, html: string, options) =>{
  const client = new ImapFlow(options)

  try {
    await client.connect()

    await client.mailboxOpen('Drafts')

    const draftMessage = {
      envelope: {
        from: 'Your Name <your_email@example.com>',
        subject: subject
      },
      content: html,
      ...options
    }

    // Append the draft to the 'Drafts' folder
    await client.append('Drafts', draftMessage, { flags: ['\Draft'] });
    console.log('Draft created successfully.');
  } catch (err) {
    console.error('Error:', err);
  } finally {
    // Close the connection
    await client.logout();
    console.log('Connection ended.');
  }
}

/*
// Example usage
const config: ImapConfig = {
    user: 'your-email@example.com',
    password: 'your-password',
    host: 'imap.your-email-provider.com',
    port: 993,
    tls: true
};

const fromAddress = 'sender@example.com';
const toAddress = 'recipient@example.com';

getMessagesFromInboxWithFilter(config, fromAddress, toAddress)
    .then(() => {
        console.log('Finished fetching filtered messages.');
    })
    .catch(err => {
        console.error('Error:', err);
    });
*/