import { ImapFlow } from 'imapflow';

const client = new ImapFlow({
  host: 'imap.gmail.com',
  port: 993,
  secure: true,
  auth: {
    user: process.env.GMAIL_EMAIL,
    pass: process.env.GMAIL_APP_PASSWORD,
  },
  logger: false,
});

await client.connect();

try {
  // Test 1: Search INBOX for indeed
  console.log('=== Searching INBOX for "indeed" ===');
  await client.mailboxOpen('INBOX');
  let uids = await client.search({ gmailraw: 'indeed' }, { uid: true });
  console.log('INBOX results:', Array.isArray(uids) ? uids.length : 0, 'messages');
  if (Array.isArray(uids) && uids.length > 0) {
    const recent = uids.slice(-5);
    for await (const msg of client.fetch(recent, { envelope: true }, { uid: true })) {
      const env = msg.envelope;
      console.log(`  [${msg.uid}] ${env?.subject} | from: ${env?.from?.[0]?.address}`);
    }
  }

  // Test 2: Search All Mail for indeed
  console.log('\n=== Searching [Gmail]/All Mail for "indeed" ===');
  await client.mailboxOpen('[Gmail]/All Mail');
  uids = await client.search({ gmailraw: 'indeed' }, { uid: true });
  console.log('All Mail results:', Array.isArray(uids) ? uids.length : 0, 'messages');
  if (Array.isArray(uids) && uids.length > 0) {
    const recent = uids.slice(-10);
    for await (const msg of client.fetch(recent, { envelope: true }, { uid: true })) {
      const env = msg.envelope;
      console.log(`  [${msg.uid}] ${env?.subject} | from: ${env?.from?.[0]?.address}`);
    }
  }

  // Test 3: Search All Mail for from:indeed
  console.log('\n=== Searching [Gmail]/All Mail for "from:donotreply@jobalert.indeed.com" ===');
  uids = await client.search({ gmailraw: 'from:donotreply@jobalert.indeed.com' }, { uid: true });
  console.log('All Mail from:indeed results:', Array.isArray(uids) ? uids.length : 0, 'messages');
  if (Array.isArray(uids) && uids.length > 0) {
    const recent = uids.slice(-5);
    for await (const msg of client.fetch(recent, { envelope: true }, { uid: true })) {
      const env = msg.envelope;
      console.log(`  [${msg.uid}] ${env?.subject} | from: ${env?.from?.[0]?.address}`);
    }
  }
} finally {
  await client.logout();
}
