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

router.get('/', async (req, res) => {
  try {
    const { rows } = await pool.query(
      'SELECT id, name, location, start_date, end_date FROM tournaments ORDER BY id DESC'
    );
    res.json(rows);
  } catch (e) {
    console.error('GET /tournaments', e);
    res.status(500).json({ error: 'server_error' });
  }
});

router.post('/', async (req, res) => {
  const { name, location, start_date, end_date } = req.body || {};
  if (!name || !start_date || !end_date) {
    return res.status(400).json({ error: 'missing_fields' });
  }
  try {
    const { rows } = await pool.query(
      `INSERT INTO tournaments (name, location, start_date, end_date)
       VALUES ($1, $2, $3, $4)
       RETURNING id, name, location, start_date, end_date`,
      [name, location || null, start_date, end_date]
    );
    res.status(201).json(rows[0]);
  } catch (e) {
    console.error('POST /tournaments', e);
    res.status(500).json({ error: 'server_error' });
  }
});

router.delete('/:id', async (req, res) => {
  const id = Number(req.params.id);
  if (!id) return res.status(400).json({ error: 'bad_id' });

  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    try { await client.query('DELETE FROM matches WHERE tournament_id = $1', [id]); } catch {}
    try { await client.query('DELETE FROM participants WHERE tournament_id = $1', [id]); } catch {}
    const result = await client.query('DELETE FROM tournaments WHERE id = $1', [id]);
    await client.query('COMMIT');
    if (result.rowCount === 0) return res.status(404).json({ error: 'not_found' });
    res.json({ ok: true, id });
  } catch (e) {
    await client.query('ROLLBACK');
    console.error('DELETE /tournaments/:id', e);
    res.status(500).json({ error: 'server_error' });
  } finally {
    client.release();
  }
});

module.exports = router;
