import '../config.js';
import sequelize from '../database.js';
import TournamentMatch from '../models/TournamentMatch.js';

const argv = process.argv.slice(2);
if (argv.length === 0) {
  console.error('Usage: node inspect_and_fix_active_matches.js <tournamentId> [--fix-all]');
  process.exit(2);
}
const tournamentId = Number(argv[0]);
const fixAll = argv.includes('--fix-all') || argv.includes('--fix');

(async () => {
  try {
    await sequelize.authenticate();
    console.log('[inspect] DB connected');

    const active = await TournamentMatch.findAll({
      where: { tournamentId, isActive: true },
      order: [['id', 'ASC']]
    });

    console.log(`[inspect] active matches for tournament ${tournamentId}: ${active.length}`);
    for (const m of active) {
      console.log(`  id=${m.id} p1=${m.player1Id} p2=${m.player2Id} isFinished=${m.isFinished} table=${m.tableNumber}`);
    }

    const candidates = await TournamentMatch.findAll({
      where: { tournamentId, isFinished: false, tableNumber: null },
      order: [['id', 'ASC']]
    });
    console.log(`[inspect] candidate matches (not finished, no table): ${candidates.length}`);
    for (const m of candidates) {
      console.log(`  id=${m.id} p1=${m.player1Id} p2=${m.player2Id} isActive=${m.isActive}`);
    }

    if (fixAll) {
      console.log('[inspect] Fix mode: resetting isActive=false for all matches in tournament');
      const [upd] = await sequelize.query('UPDATE tournament_match SET is_active = 0 WHERE tournament_id = :t', { replacements: { t: tournamentId } });
      console.log('[inspect] Raw update result:', upd);

      const nowActive = await TournamentMatch.count({ where: { tournamentId, isActive: true } });
      console.log('[inspect] Remaining active matches:', nowActive);
    }

    process.exit(0);
  } catch (err) {
    console.error('[inspect] Error:', err);
    process.exit(3);
  }
})();
