import { getAllSyncedAccounts, getUserById } from 'officerdb';
import { performResync } from './resync';

const INTERVAL_MS = 10 * 60 * 1000; // 10 minutes

let timer: ReturnType<typeof setInterval> | null = null;

async function tick() {
  try {
    const accounts = await getAllSyncedAccounts();
    if (accounts.length === 0) return;

    for (const account of accounts) {
      const user = await getUserById(account.userId);
      if (!user) continue;

      try {
        console.log(`[email-cron] Resyncing ${account.email}`);
        const result = await performResync({ accountId: account.id, userEmail: user.email, userId: user.id });
        if (result.saved > 0) {
          console.log(`[email-cron] ${account.email}: ${result.saved} new emails`);
        }
      } catch (err) {
        console.error(`[email-cron] Failed to resync ${account.email}:`, err instanceof Error ? err.message : err);
      }
    }
  } catch (err) {
    console.error('[email-cron] Error:', err instanceof Error ? err.message : err);
  }
}

export function initEmailCron() {
  if (timer) return;
  console.log(`[email-cron] Starting email sync cron (every ${INTERVAL_MS / 60_000} min)`);
  timer = setInterval(tick, INTERVAL_MS);
  setTimeout(tick, 30_000);
}

export function stopEmailCron() {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
}
