import { Router } from 'express';
import { query } from '../db.js';
import { requireAuth } from '../middleware/auth.js';

const router = Router();

// Public
router.get('/', async (req, res) => {
  const r = await query(`SELECT id, name, location, start_date, end_date FROM tournaments ORDER BY start_date DESC NULLS LAST, id DESC LIMIT 50`);
  res.json(r.rows);
});

router.get('/:id', async (req, res) => {
  const { id } = req.params;
  const r = await query(`SELECT id, name, location, start_date, end_date, description FROM tournaments WHERE id=$1`, [id]);
  if(!r.rowCount) return res.status(404).json({error:'Not found'});
  res.json(r.rows[0]);
});

router.get('/:id/participants', async (req, res) => {
  const { id } = req.params;
  const r = await query(`SELECT p.id, p.name, p.rating FROM participants p WHERE p.tournament_id=$1 ORDER BY p.name`, [id]);
  res.json(r.rows);
});

router.get('/:id/matches', async (req, res) => {
  const { id } = req.params;
  const r = await query(`SELECT id, court, start_time, team_a, team_b, score_a, score_b, finished FROM matches WHERE tournament_id=$1 ORDER BY start_time, id`, [id]);
  res.json(r.rows);
});

// Admin
router.post('/', requireAuth, async (req, res) => {
  const { name, location, start_date, end_date, description } = req.body || {};
  if(!name) return res.status(400).json({error:'name required'});
  const r = await query(
    `INSERT INTO tournaments(name, location, start_date, end_date, description)
     VALUES ($1,$2,$3,$4,$5) RETURNING id`,
    [name, location||null, start_date||null, end_date||null, description||null]
  );
  res.status(201).json({ id: r.rows[0].id });
});

router.post('/:id/participants', requireAuth, async (req, res) => {
  const { id } = req.params;
  const { name, rating } = req.body || {};
  if(!name) return res.status(400).json({error:'name required'});
  const r = await query(
    `INSERT INTO participants(tournament_id, name, rating) VALUES ($1,$2,$3) RETURNING id`,
    [id, name, rating||null]
  );
  res.status(201).json({ id: r.rows[0].id });
});

router.post('/:id/generate-americano', requireAuth, async (req, res) => {
  const { id } = req.params;
  const { courts = [], start = null, slotMinutes = 20 } = req.body || {};
  // Minimal placeholder generator: pairs consecutive participants; schedule sequentially per court
  const p = await query(`SELECT id, name FROM participants WHERE tournament_id=$1 ORDER BY id`, [id]);
  if(p.rows.length < 4) return res.status(400).json({error:'Need at least 4 participants'});
  const pairs = [];
  for(let i=0;i<p.rows.length;i+=2){
    if(i+1<p.rows.length) pairs.push([p.rows[i], p.rows[i+1]]);
  }
  const courtsArr = Array.isArray(courts) && courts.length ? courts : ['Court 1', 'Court 2'];
  const startTime = start ? new Date(start) : new Date(Date.now()+10*60*1000);
  const matches = [];
  let t = new Date(startTime);
  let courtIdx = 0;
  for(const pair of pairs){
    const court = courtsArr[courtIdx % courtsArr.length];
    matches.push({ court, start_time: t.toISOString(), team_a: pair[0].name, team_b: pair[1].name });
    t = new Date(t.getTime() + slotMinutes*60*1000);
    courtIdx++;
  }
  const inserted = [];
  for(const m of matches){
    const r = await query(
      `INSERT INTO matches(tournament_id, court, start_time, team_a, team_b) VALUES ($1,$2,$3,$4,$5) RETURNING id`,
      [id, m.court, m.start_time, m.team_a, m.team_b]
    );
    inserted.push(r.rows[0].id);
  }
  res.json({ created: inserted.length, match_ids: inserted });
});

export default router;
