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

// GET /api/tournaments/:id/participants
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 id, tournament_id, full_name FROM participants WHERE tournament_id = $1 ORDER BY id DESC',
      [id]
    );
    res.json(rows);
  } catch (e) {
    console.error('GET participants by tournament', e);
    res.status(500).json({ error: 'server_error' });
  }
});

// POST /api/participants  { tournament_id, full_name }
router.post('/', async (req, res) => {
  const { tournament_id, full_name } = req.body || {};
  const tid = Number(tournament_id);
  if (!tid || !full_name || !full_name.trim()) {
    return res.status(400).json({ error: 'missing_fields' });
  }
  try {
    const { rows } = await pool.query(
      'INSERT INTO participants (tournament_id, full_name) VALUES ($1, $2) RETURNING id, tournament_id, full_name',
      [tid, full_name.trim()]
    );
    res.status(201).json(rows[0]);
  } catch (e) {
    console.error('POST /participants', e);
    res.status(500).json({ error: 'server_error' });
  }
});

module.exports = router;
