require('dotenv').config({ override: true });
const express = require('express');
const cors    = require('cors');

const auth = require('./middleware/auth');
const { requireSuperAdmin, requireAdmin, requireUser, filterByRegion } = require('./middleware/roles');

const app  = express();
const PORT = process.env.PORT || 3001;

app.use(cors());
app.use(express.json());
app.use(express.static(__dirname));

// ─── Public ──────────────────────────────────────────────────────────────────

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', project: 'RLA API v1', date: new Date().toISOString() });
});

app.use('/api/auth', require('./routes/auth'));

// ─── Protégées (user+) ───────────────────────────────────────────────────────

app.use('/api/marches',          auth, requireUser, filterByRegion, require('./routes/marches'));
app.use('/api/stats',            auth, requireUser, filterByRegion, require('./routes/stats'));
app.use('/api/synthese',         auth, requireUser, filterByRegion, require('./routes/synthese'));
app.use('/api/alertes',          auth, requireUser, filterByRegion, require('./routes/alertes'));
app.use('/api/en-service',       auth, requireUser, filterByRegion, require('./routes/en-service'));
app.use('/api/en-cours',         auth, requireUser, filterByRegion, require('./routes/en-cours'));
app.use('/api/par-region',       auth, requireUser, filterByRegion, require('./routes/par-region'));
app.use('/api/clotures',         auth, requireUser, filterByRegion, require('./routes/clotures'));
app.use('/api/pilotage-proactif',auth, requireUser, filterByRegion, require('./routes/pilotage'));
app.use('/api/matrice-risque',   auth, requireUser, filterByRegion, require('./routes/matrice-risque'));
app.use('/api/export',           auth, requireUser, filterByRegion, require('./routes/export'));

// ─── Protégées (admin+) ──────────────────────────────────────────────────────

app.use('/api/pipeline', auth, requireAdmin, require('./routes/pipeline'));

// ─── Protégées (superadmin) ──────────────────────────────────────────────────

app.use('/api/users', auth, requireSuperAdmin, require('./routes/users'));
app.use('/api/logs',  auth, requireSuperAdmin, require('./routes/logs'));

// ─── Start ───────────────────────────────────────────────────────────────────

app.listen(PORT, () => {
  console.log(`RLA API v1 démarrée sur le port ${PORT}`);
  console.log(`Endpoints disponibles sur http://localhost:${PORT}/api/`);
});
