/**
 * cache-worker — pre-compute discover, finance, travel
 * docs/architecture: 03-cache-and-precompute-strategy.md
 * Cron: discover every 15m, finance every 2m, travel every 4h
 * Usage: node run.js --task=discover|finance|travel|all
 */

import Redis from 'ioredis';
import { runDiscoverPrecompute } from './tasks/discover.js';
import { runFinancePrecompute } from './tasks/finance.js';
import { runTravelPrecompute } from './tasks/travel.js';

const REDIS_URL = process.env.REDIS_URL ?? 'redis://localhost:6379';
const DISCOVER_SVC_URL = process.env.DISCOVER_SVC_URL ?? 'http://localhost:3002';
const FINANCE_SVC_URL = process.env.FINANCE_SVC_URL ?? 'http://localhost:3003';
const TRAVEL_SVC_URL = process.env.TRAVEL_SVC_URL ?? 'http://localhost:3004';

function getTask(): string {
  const idx = process.argv.indexOf('--task');
  return idx >= 0 && process.argv[idx + 1] ? process.argv[idx + 1] : 'all';
}

async function main() {
  const task = getTask();
  // @ts-expect-error — ioredis + NodeNext ESM constructability
  const redis = new Redis(REDIS_URL);
  try {
    if (task === 'discover' || task === 'all') {
      console.log('[cache-worker] Running discover precompute...');
      await runDiscoverPrecompute(redis, DISCOVER_SVC_URL);
    }
    if (task === 'finance' || task === 'all') {
      console.log('[cache-worker] Running finance precompute...');
      await runFinancePrecompute(redis, FINANCE_SVC_URL);
    }
    if (task === 'travel' || task === 'all') {
      console.log('[cache-worker] Running travel precompute...');
      await runTravelPrecompute(redis, TRAVEL_SVC_URL);
    }
    console.log('[cache-worker] Done');
  } finally {
    await redis.quit();
  }
}

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