import { searchMessages } from './imap.js';
import { sendSupportEmailAlert } from './notifications/slack.js';
import redis from './redis.js';

const REDIS_KEY = 'support:email:alerted_uids';
const POLL_INTERVAL_MS = 5 * 60 * 1000;

async function pollSupportInbox() {
  try {
    const messages = await searchMessages('', 20, 'sqcp_support');
    if (messages.length === 0) return;

    const alreadyAlerted = await redis.sMembers(REDIS_KEY);
    const alerted = new Set(alreadyAlerted);

    for (const msg of messages) {
      if (msg.seen) continue;
      const key = String(msg.uid);
      if (alerted.has(key)) continue;

      await sendSupportEmailAlert({
        uid: msg.uid,
        subject: msg.subject,
        from: msg.from,
        date: msg.date,
      });

      await redis.sAdd(REDIS_KEY, key);
      // Keep the set from growing unbounded — trim to last 500 UIDs
      await redis.expire(REDIS_KEY, 60 * 60 * 24 * 30); // 30-day TTL
      console.log(`[email-poller] alerted on uid=${msg.uid} from=${msg.from}`);
    }
  } catch (err) {
    console.error('[email-poller] poll error:', (err as Error).message);
  }
}

export function startEmailPoller() {
  console.log('[email-poller] starting — polling support@squaremcp.com every 5 min');
  pollSupportInbox();
  setInterval(pollSupportInbox, POLL_INTERVAL_MS);
}
