import '../config.js';
import sequelize from '../database.js';
import { Op } from 'sequelize';
import UserToken from '../models/UserToken.js';
import User from '../models/User.js';
import UserClub from '../models/UserClub.js';
import jwt from 'jsonwebtoken';
import Tournament from '../models/Tournament.js';
import tournamentService from '../services/tournamentService.js';

async function run() {
  try {
    await sequelize.authenticate();
    console.log('[test] DB connected');

    const tokenCandidates = await UserToken.findAll({ where: { expiresAt: { [Op.gt]: new Date() } }, limit: 50 });
    let token = null;

    const tournaments = await Tournament.findAll({ limit: 50 });
    if (!tournaments || tournaments.length === 0) {
      console.error('[test] No tournaments found');
      process.exit(1);
    }

    let performed = false;
    for (const tournamentItem of tournaments) {
      // try to find token for this tournament's club
      for (const t of tokenCandidates) {
        try {
          const payload = jwt.verify(t.token, process.env.JWT_SECRET);
          const user = await User.findByPk(payload.userId);
          if (!user) continue;
          const uc = await UserClub.findOne({ where: { user_id: user.id, club_id: tournamentItem.clubId, approved: true } });
          if (!uc) continue;
          // found suitable token and tournament
          token = t.token;
          console.log('[test] Using token id=', t.id, 'userId=', user.id, 'for tournament id=', tournamentItem.id);
          const newNumber = 7;
          const updated = await tournamentService.updateTournament(token, tournamentItem.clubId, tournamentItem.id, tournamentItem.name, tournamentItem.date, tournamentItem.winningSets, newNumber);
          console.log('[test] Update successful for tournament', tournamentItem.id, 'numberOfTables now=', updated.numberOfTables);
          performed = true;
          break;
        } catch (e) {
          continue;
        }
      }
      if (performed) break;
    }

    if (!performed) {
      console.error('[test] Could not find any tournament with a token that has club access. Falling back to direct DB update test.');
      const t0 = tournaments[0];
      const old = t0.numberOfTables;
      t0.numberOfTables = 11;
      await t0.save();
      console.log('[test] Direct DB update successful. tournament id=', t0.id, 'old=', old, 'new=', t0.numberOfTables);
      process.exit(0);
    }
    process.exit(0);
  } catch (err) {
    console.error('[test] Error:', err);
    process.exit(2);
  }
}

run();
