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 Tournament from '../models/Tournament.js';

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

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

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

    let usedToken = null;
    let targetTournament = null;

    for (const tItem of tournaments) {
      for (const tc of tokenCandidates) {
        try {
          const payload = JSON.parse(Buffer.from(tc.token.split('.')[1] || '', 'base64').toString('utf8'));
          const user = await User.findByPk(payload.userId);
          if (!user) continue;
          const uc = await UserClub.findOne({ where: { user_id: user.id, club_id: tItem.clubId, approved: true } });
          if (uc) { usedToken = tc.token; targetTournament = tItem; break; }
        } catch (e) {
          continue;
        }
      }
      if (usedToken) break;
    }

    if (!usedToken) {
      console.error('[api-test] No token with club access found');
      process.exit(1);
    }

    console.log('[api-test] Using token for tournament', targetTournament.id, 'club', targetTournament.clubId);

    const url = `http://localhost:3005/api/tournament/${targetTournament.clubId}/${targetTournament.id}`;
    const payload = {
      name: targetTournament.name || 'Test Tournament',
      date: targetTournament.date,
      winningSets: targetTournament.winningSets || 3,
      numberOfTables: 9
    };

    const res = await fetch(url, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'authcode': usedToken
      },
      body: JSON.stringify(payload)
    });

    console.log('[api-test] HTTP status', res.status);
    const body = await res.text();
    console.log('[api-test] Response body:', body);
    process.exit(res.ok ? 0 : 2);
  } catch (err) {
    console.error('[api-test] Error:', err);
    process.exit(3);
  }
}

run();
