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 {
  await client.mailboxOpen('[Gmail]/All Mail');
  const uids = await client.search({ gmailraw: 'from:donotreply@jobalert.indeed.com after:2026/04/21' }, { uid: true });
  console.log('Indeed emails today:', Array.isArray(uids) ? uids.length : 0, 'messages\n');
  if (Array.isArray(uids) && uids.length > 0) {
    for await (const msg of client.fetch(uids, { envelope: true }, { uid: true })) {
      const env = msg.envelope;
      console.log(`- ${env?.subject}`);
    }
  } else {
    console.log('No emails found. Trying broader search for "indeed" today...');
    const uids2 = await client.search({ gmailraw: 'indeed after:2026/04/21' }, { uid: true });
    console.log('Broader "indeed" today:', Array.isArray(uids2) ? uids2.length : 0, 'messages\n');
    if (Array.isArray(uids2) && uids2.length > 0) {
      for await (const msg of client.fetch(uids2, { envelope: true }, { uid: true })) {
        const env = msg.envelope;
        const from = env?.from?.[0]?.address ?? '';
        if (from.includes('indeed')) {
          console.log(`- ${env?.subject} | from: ${from}`);
        }
      }
    }
  }
} finally {
  await client.logout();
}
