#!/usr/bin/env node

const Imap = require('imap');
const { simpleParser } = require('mailparser');
const readline = require('readline');
const util = require('util');

// Create readline interface for password input
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Promisify the question method
const question = util.promisify((query, callback) => {
  rl.question(query, (answer) => callback(null, answer));
});

async function testMailbox(username, password, server = 'mail.2weekmail.fyi', port = 993) {
  return new Promise((resolve, reject) => {
    try {
      console.log(`Connecting to ${server}:${port}...`);
      
      const imap = new Imap({
        user: username,
        password: password,
        host: server,
        port: port,
        tls: true,
        tlsOptions: { rejectUnauthorized: false } // For testing with self-signed certs
      });

      function openInbox(cb) {
        imap.openBox('INBOX', false, cb);
      }

      imap.once('ready', () => {
        console.log(`Login successful as ${username}!`);
        
        // List mailboxes
        imap.getBoxes((err, boxes) => {
          if (err) throw err;
          
          console.log('\nAvailable mailboxes:');
          Object.keys(boxes).forEach(box => {
            console.log(`  - ${box}`);
            if (boxes[box].children) {
              Object.keys(boxes[box].children).forEach(child => {
                console.log(`    - ${box}${boxes[box].delimiter}${child}`);
              });
            }
          });
          
          // Open inbox
          console.log('\nSelecting INBOX...');
          openInbox((err, box) => {
            if (err) throw err;
            
            console.log(`Found ${box.messages.total} message(s) in INBOX`);
            
            // If no messages, close connection
            if (box.messages.total === 0) {
              imap.end();
              console.log('\nLogout successful');
              resolve(true);
              return;
            }
            
            // Get the last 10 messages (or all if less than 10)
            const numMessages = Math.min(box.messages.total, 10);
            const start = box.messages.total - numMessages + 1;
            const fetch = imap.seq.fetch(`${start}:*`, {
              bodies: ['HEADER.FIELDS (FROM TO SUBJECT DATE)'],
              struct: true
            });
            
            console.log('\nMessage list:');
            let counter = 1;
            
            fetch.on('message', (msg, seqno) => {
              msg.on('body', (stream, info) => {
                let buffer = '';
                
                stream.on('data', (chunk) => {
                  buffer += chunk.toString('utf8');
                });
                
                stream.once('end', () => {
                  simpleParser(buffer, (err, parsed) => {
                    if (err) {
                      console.error(`Error parsing message: ${err}`);
                      return;
                    }
                    
                    console.log(`  ${counter}. From: ${parsed.from?.text || 'Unknown'}`);
                    console.log(`     Subject: ${parsed.subject || 'No Subject'}`);
                    console.log(`     Date: ${parsed.date || 'Unknown'}`);
                    console.log(`     ID: ${seqno}`);
                    console.log('     ' + '-'.repeat(40));
                    
                    counter++;
                  });
                });
              });
            });
            
            fetch.once('error', (err) => {
              console.error(`Fetch error: ${err}`);
              reject(err);
            });
            
            fetch.once('end', () => {
              imap.end();
              console.log('\nLogout successful');
              resolve(true);
            });
          });
        });
      });

      imap.once('error', (err) => {
        console.error(`IMAP Error: ${err}`);
        reject(err);
      });

      imap.once('end', () => {
        console.log('Connection ended');
        rl.close();
      });

      imap.connect();
      
    } catch (error) {
      console.error(`Error: ${error}`);
      reject(error);
    }
  });
}

async function main() {
  if (process.argv.length < 3) {
    console.log('Usage: node test_mailbox.js username@domain.com [server] [port]');
    process.exit(1);
  }

  const username = process.argv[2];
  const server = process.argv.length > 3 ? process.argv[3] : 'mail.2weekmail.fyi';
  const port = process.argv.length > 4 ? parseInt(process.argv[4]) : 993;

  try {
    // Get password securely
    const password = await question(`Enter password for ${username}: `);
    
    const success = await testMailbox(username, password, server, port);
    
    if (success) {
      console.log('\nMailbox test completed successfully!');
      process.exit(0);
    } else {
      console.log('\nMailbox test failed!');
      process.exit(1);
    }
  } catch (error) {
    console.error('\nMailbox test failed with error:', error);
    process.exit(1);
  }
}

main();