import 'dotenv/config';

import dbPool from '../db';
import { runMlbMarketCompletionCron } from '../cron/mlb-market-completion';

const POLL_INTERVAL_MS = Number(process.env.MLB_MARKET_COMPLETION_INTERVAL_MS || 60_000);

let stopped = false;
let timer: NodeJS.Timeout | null = null;

function scheduleNextRun(): void {
  if (stopped) return;
  timer = setTimeout(() => {
    runOnce().catch((err) => {
      console.error('[mlb-market-completion-scheduler] uncaught run error:', err);
    });
  }, POLL_INTERVAL_MS);
}

async function runOnce(): Promise<void> {
  if (stopped) return;

  try {
    const result = await runMlbMarketCompletionCron();
    console.log('[mlb-market-completion-scheduler] run complete', JSON.stringify(result));
  } catch (err) {
    console.error('[mlb-market-completion-scheduler] run failed:', err);
  } finally {
    scheduleNextRun();
  }
}

async function shutdown(signal: string): Promise<void> {
  if (stopped) return;
  stopped = true;
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  console.log(`[mlb-market-completion-scheduler] shutting down on ${signal}`);
  await dbPool.end().catch(() => {});
  process.exit(0);
}

process.on('SIGINT', () => {
  shutdown('SIGINT').catch(() => process.exit(1));
});

process.on('SIGTERM', () => {
  shutdown('SIGTERM').catch(() => process.exit(1));
});

runOnce().catch((err) => {
  console.error('[mlb-market-completion-scheduler] fatal startup error:', err);
  shutdown('startup_error').catch(() => process.exit(1));
});
