import { Router } from 'express';
import pool from '../db.js';

const router = Router();

// GET /api/tournaments/:id/standings
router.get('/:id/standings', async (req, res) => {
  const tid = Number(req.params.id);
  if (!tid) return res.status(400).json({ error: 'bad_tournament_id' });

  const { rows: players } = await pool.query('select id, full_name from participants where tournament_id=$1', [tid]);
  const { rows: matches } = await pool.query('select * from matches where tournament_id=$1 order by id', [tid]);

  const nameToId = new Map(players.map(p => [p.full_name, p.id]));
  const stats = new Map(players.map(p => [p.id, {
    player_id: p.id, name: p.full_name,
    played: 0, wins: 0, draws: 0, losses: 0,
    games_for: 0, games_against: 0, points: 0
  }]));

  const addStats = (pid, gf, ga, wdl) => {
    const s = stats.get(pid);
    s.played += 1;
    s.games_for += gf;
    s.games_against += ga;
    if (wdl === 'W') s.wins += 1;
    else if (wdl === 'D') s.draws += 1;
    else if (wdl === 'L') s.losses += 1;
    s.points += gf; // Americano style: points = games won
  };

  for (const m of matches) {
    if (!m.team_a || !m.team_b) continue;
    const aNames = m.team_a.split('&').map(s => s.trim());
    const bNames = m.team_b.split('&').map(s => s.trim());
    const aIds = aNames.map(n => nameToId.get(n)).filter(Boolean);
    const bIds = bNames.map(n => nameToId.get(n)).filter(Boolean);

    const sa = Number(m.score_a || 0);
    const sb = Number(m.score_b || 0);
    const considered = m.done === true || sa > 0 || sb > 0;
    if (!considered) continue;

    let outcomeA = 'D', outcomeB = 'D';
    if (sa > sb) { outcomeA = 'W'; outcomeB = 'L'; }
    else if (sb > sa) { outcomeA = 'L'; outcomeB = 'W'; }

    for (const pid of aIds) addStats(pid, sa, sb, outcomeA);
    for (const pid of bIds) addStats(pid, sb, sa, outcomeB);
  }

  const table = Array.from(stats.values()).map(s => ({
    ...s,
    diff: s.games_for - s.games_against,
    rank_key: [-(s.points), -(s.diff), -(s.wins), s.name.toLowerCase()]
  }));

  table.sort((x, y) => {
    for (let i = 0; i < x.rank_key.length; i++) {
      if (x.rank_key[i] < y.rank_key[i]) return -1;
      if (x.rank_key[i] > y.rank_key[i]) return 1;
    }
    return 0;
  });

  let rank = 0, prevKey = null;
  for (const row of table) {
    const key = JSON.stringify(row.rank_key);
    if (key !== prevKey) rank += 1;
    row.rank = rank;
    prevKey = key;
    delete row.rank_key;
  }

  res.json({ tournament_id: tid, standings: table });
});

export default router;
