import dotenv from 'dotenv';
import path from 'path';
dotenv.config({ path: path.join(__dirname, '../../.env') });

import pool from '../db';
import { shouldVoidArchivedMmaMatchup, type UfcFightRow } from '../lib/mma-archive-validation';
import { refreshBucketStats, voidArchivedForecast } from '../services/archive';

async function main() {
  console.log(`[${new Date().toISOString()}] Voiding invalid MMA archives...`);

  const { rows: pending } = await pool.query(
    `SELECT id, home_team, away_team, starts_at
     FROM rm_archived_forecasts
     WHERE outcome = 'pending'
       AND league = 'mma'
     ORDER BY starts_at DESC`
  );

  let voided = 0;

  for (const archive of pending) {
    const fightsResult = await pool.query(
      `SELECT f."fighter1Name" AS "fighter1Name",
              f."fighter2Name" AS "fighter2Name",
              e.name AS "eventName"
       FROM "UfcFight" f
       JOIN "UfcEvent" e ON e."eventId" = f."eventId"
       WHERE e.date::date >= ($1::timestamptz - interval '1 day')::date
         AND e.date::date <= ($1::timestamptz + interval '1 day')::date
       ORDER BY e.date DESC, f.id DESC`,
      [archive.starts_at],
    );

    const fights = fightsResult.rows as UfcFightRow[];
    if (!shouldVoidArchivedMmaMatchup(archive, fights)) continue;

    const eventName = fights[0]?.eventName || 'verified UFC card';
    const reason = `void: archived matchup not on verified UFC card (${eventName})`;
    await voidArchivedForecast(archive.id, reason);
    voided++;
    console.log(`  Voided: ${archive.away_team} @ ${archive.home_team} (${eventName})`);
  }

  await refreshBucketStats();
  console.log(`Void complete. Voided ${voided}/${pending.length} pending MMA archives.`);
  await pool.end();
}

main().catch((err) => {
  console.error('Void invalid MMA archives failed:', err);
  process.exit(1);
});
