const express = require('express');
const router = express.Router();
const { pool } = require('../db');

/**
 * Schema attendu (observé chez toi) :
 * - matches: id, tournament_id, team_a_id, team_b_id, court?, start_time?, status text default 'scheduled', finished bool
 * - (optionnel) score_a, score_b  → si absents, on peut les créer via migration fournie
 */

// Création d'un match (équipes)
router.post('/', async (req, res) => {
  const { tournament_id, team_a_id, team_b_id, court, start_time, status } = req.body || {};
  const tid = Number(tournament_id);
  if (!tid) return res.status(400).json({ error: 'missing_tournament_id' });
  try {
    const { rows } = await pool.query(
      `INSERT INTO matches (tournament_id, team_a_id, team_b_id, court, start_time, status)
       VALUES ($1, $2, $3, $4, $5, COALESCE($6,'scheduled'))
       RETURNING *`,
      [tid, team_a_id || null, team_b_id || null, court || null, start_time || null, status || null]
    );
    res.status(201).json(rows[0]);
  } catch (e) {
    console.error('POST /matches error:', e);
    res.status(500).json({ error: 'server_error', detail: e.message });
  }
});

// Liste (option tournoi)
router.get('/', async (req, res) => {
  const tid = Number(req.query.tid || 0);
  try {
    const { rows } = await pool.query(
      tid
        ? `SELECT * FROM matches WHERE tournament_id = $1 ORDER BY id DESC`
        : `SELECT * FROM matches ORDER BY id DESC`,
      tid ? [tid] : []
    );
    res.json(rows);
  } catch (e) {
    console.error('GET /matches', e);
    res.status(500).json({ error: 'server_error' });
  }
});

// Alias: GET /api/tournaments/:id/matches
router.get('/by-tournament/:id', async (req, res) => {
  const id = Number(req.params.id);
  if (!id) return res.status(400).json({ error: 'bad_tournament_id' });
  try {
    const { rows } = await pool.query(`SELECT * FROM matches WHERE tournament_id = $1 ORDER BY id DESC`, [id]);
    res.json(rows);
  } catch (e) {
    console.error('GET /matches/by-tournament/:id', e);
    res.status(500).json({ error: 'server_error' });
  }
});

// Score d'un match
// Si score_a/score_b n'existent pas encore, répond avec un message clair (et fournir migration)
router.post('/:id/score', async (req, res) => {
  const id = Number(req.params.id);
  if (!id) return res.status(400).json({ error: 'bad_id' });
  const { score_a, score_b, finished } = req.body || {};

  // Construire SET dynamiquement
  const sets = [];
  const vals = [];
  let i = 1;
  if (typeof score_a === 'number') { sets.push(`score_a = $${i++}`); vals.push(score_a); }
  if (typeof score_b === 'number') { sets.push(`score_b = $${i++}`); vals.push(score_b); }
  if (typeof finished === 'boolean') { sets.push(`finished = $${i++}`); vals.push(finished); }

  if (sets.length === 0) return res.status(400).json({ error: 'no_fields' });
  vals.push(id);

  try {
    const q = `UPDATE matches SET ${sets.join(', ')} WHERE id = $${i} RETURNING *`;
    const { rows } = await pool.query(q, vals);
    if (rows.length === 0) return res.status(404).json({ error: 'not_found' });
    res.json(rows[0]);
  } catch (e) {
    // Si colonne inexistante → proposer la migration
    if (e && e.code === '42703') {
      return res.status(409).json({
        error: 'missing_columns',
        detail: 'Les colonnes score_a/score_b sont absentes. Exécutez la migration SQL fournie pour les ajouter.'
      });
    }
    console.error('POST /matches/:id/score', e);
    res.status(500).json({ error: 'server_error' });
  }
});

// Update générique (équipes, court, start_time, status, finished)
router.put('/:id', async (req, res) => {
  const id = Number(req.params.id);
  if (!id) return res.status(400).json({ error: 'bad_id' });

  const allowed = ['team_a_id','team_b_id','court','start_time','status','finished','tournament_id'];
  const sets = [];
  const vals = [];
  let i = 1;
  for (const k of allowed) {
    if (Object.prototype.hasOwnProperty.call(req.body, k)) {
      sets.push(`${k} = $${i++}`);
      vals.push(req.body[k]);
    }
  }
  if (sets.length === 0) return res.status(400).json({ error: 'no_fields' });
  vals.push(id);

  try {
    const { rows } = await pool.query(`UPDATE matches SET ${sets.join(', ')} WHERE id = $${i} RETURNING *`, vals);
    if (rows.length === 0) return res.status(404).json({ error: 'not_found' });
    res.json(rows[0]);
  } catch (e) {
    console.error('PUT /matches/:id', e);
    res.status(500).json({ error: 'server_error' });
  }
});

// Suppression
router.delete('/:id', async (req, res) => {
  const id = Number(req.params.id);
  if (!id) return res.status(400).json({ error: 'bad_id' });
  try {
    const result = await pool.query(`DELETE FROM matches WHERE id = $1`, [id]);
    if (result.rowCount === 0) return res.status(404).json({ error: 'not_found' });
    res.json({ ok: true, id });
  } catch (e) {
    console.error('DELETE /matches/:id', e);
    res.status(500).json({ error: 'server_error' });
  }
});

module.exports = router;
