/**
 * VPS / non-Vercel cron entry point.
 *
 * On Vercel, vercel.json's `crons` array hits these routes directly and
 * this script isn't needed. On a VPS (or any host without built-in cron),
 * point system cron / systemd timers at this script instead:
 *
 *   crontab -e
 *   */15 * * * * cd /path/to/app && npm run cron:discover >> /var/log/gamesji-cron.log 2>&1
 *   */20 * * * * cd /path/to/app && npm run cron:generate >> /var/log/gamesji-cron.log 2>&1
 *   0 3 * * *    cd /path/to/app && npm run cron:refresh  >> /var/log/gamesji-cron.log 2>&1
 *   */30 * * * * cd /path/to/app && npm run cron:rss      >> /var/log/gamesji-cron.log 2>&1
 *
 * Requires the app to already be running (`npm start` / pm2 / systemd) at
 * the URL in NEXT_PUBLIC_SITE_URL, and CRON_SECRET set in the environment
 * this script runs in.
 */

const JOB_PATHS: Record<string, string> = {
  'discover-games': '/api/cron/discover-games',
  'generate-content': '/api/cron/generate-content',
  'refresh-stale': '/api/cron/refresh-stale',
  'fetch-rss': '/api/cron/fetch-rss',
};

async function main() {
  const job = process.argv[2];
  const path = job && JOB_PATHS[job];
  if (!path) {
    console.error(`Usage: tsx scripts/run-cron.ts <${Object.keys(JOB_PATHS).join('|')}>`);
    process.exit(1);
  }

  const secret = process.env.CRON_SECRET;
  if (!secret) {
    console.error('CRON_SECRET is not set in this shell/environment.');
    process.exit(1);
  }

  const siteUrl = (process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000').replace(/\/$/, '');

  const res = await fetch(`${siteUrl}${path}`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${secret}` },
  });

  const body = await res.text();
  console.log(`[${new Date().toISOString()}] ${job} -> ${res.status}: ${body}`);

  if (!res.ok) process.exit(1);
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
