const express = require('express');
const app = express();
app.use(express.json());

// Health
app.get('/api/health', (req, res) => res.json({ ok: true, ts: Date.now() }));

// Routes
app.use('/api/tournaments', require('./routes/tournaments'));
app.use('/api/participants', require('./routes/participants'));

// "by tournament" nicer path
app.get('/api/tournaments/:id/participants', (req, res, next) => {
  req.url = '/by-tournament/' + req.params.id;
  return require('./routes/participants')(req, res, next);
});

// 404 for unknown API paths
app.use('/api', (req, res) => res.status(404).json({ error: 'not_found' }));

const PORT = Number(process.env.PORT || 4000);
app.listen(PORT, () => console.log(`API listening on :${PORT}`));

app.use('/api/participants', require('./routes/participants'));
app.get('/api/tournaments/:id/participants', (req,res,next)=>{
  req.url = '/by-tournament/' + req.params.id;
  return require('./routes/participants')(req,res,next);
});
