import pino from 'pino';
import { loadEnv } from '../config/env.js';
import { createDatabase } from '../db/database.js';
import { migrate } from '../db/migrations.js';

const env = loadEnv();
const logger = pino({ level: env.LOG_LEVEL });
const db = await createDatabase(env);
await migrate(db);

async function tick() {
  const reset = await db.query(
    `UPDATE jobs SET status = 'queued', locked_at = NULL, locked_by = NULL,
      available_at = now() + interval '30 seconds', last_error = COALESCE(last_error, '') || ' | recovered stale lock'
     WHERE status = 'processing' AND locked_at < now() - interval '15 minutes' AND attempts < max_attempts`
  );
  const failed = await db.query(
    `UPDATE jobs SET status = 'failed', locked_at = NULL, locked_by = NULL,
      last_error = COALESCE(last_error, '') || ' | retry limit reached by scheduler'
     WHERE status IN ('queued','processing') AND attempts >= max_attempts`
  );
  if (reset.rowCount || failed.rowCount) logger.info({ reset: reset.rowCount, failed: failed.rowCount }, 'scheduler recovered jobs');
}

await tick();
const timer = setInterval(() => void tick().catch((error) => logger.error({ err: error }, 'scheduler tick failed')), 60_000);
async function stop() { clearInterval(timer); await db.close(); process.exit(0); }
process.on('SIGTERM', () => void stop());
process.on('SIGINT', () => void stop());
