/**
 * GET /api/pilotage-proactif
 * Pilotage proactif : classement par niveau d'avancement vs seuils
 */
const express = require('express');
const router  = express.Router();
const { getMarches } = require('../services/baserow');
const {
  isCloture, normalizeMarche, parseNum,
  niveauAvancement, getDelaiRestant, niveauAlerte,
  SEUIL_STANDARD, SEUIL_MODERNISATION, SEUIL_CRITIQUE_PCT,
} = require('../services/calc');

router.get('/', async (req, res) => {
  try {
    const { region, entrepreneur, nature, niveau } = req.query;
    const regionFilter = req.regionFilter;

    let rows = await getMarches();

    rows = rows.filter(r => !isCloture(r));

    // Filtres
    if (regionFilter) rows = rows.filter(r => r.region === regionFilter);
    else if (region)  rows = rows.filter(r => r.region === region);
    if (entrepreneur) rows = rows.filter(r => String(r.entrepreneur || '').toLowerCase().includes(entrepreneur.toLowerCase()));
    if (nature)       rows = rows.filter(r => String(r.nature || '').toLowerCase().includes(nature.toLowerCase()));

    const items = rows.map(r => {
      const m      = normalizeMarche(r);
      const delai  = getDelaiRestant(r);
      return {
        ...m,
        delai_restant: delai,
        niveau_alerte: niveauAlerte(delai),
        niveau_avancement: niveauAvancement(r.taux_phy ?? r.avt_phy, r.nature),
      };
    });

    // Groupement
    const normal         = items.filter(r => r.niveau_avancement === 'normal');
    const sous_avancement = items.filter(r => r.niveau_avancement === 'sous_avancement');
    const depasse        = items.filter(r => r.niveau_avancement === 'dépassé');

    // Si filtre sur niveau
    let result = items;
    if (niveau === 'normal')          result = normal;
    else if (niveau === 'sous')       result = sous_avancement;
    else if (niveau === 'depasse')    result = depasse;

    res.json({
      seuils: {
        standard:      SEUIL_STANDARD,
        modernisation: SEUIL_MODERNISATION,
        critique:      SEUIL_CRITIQUE_PCT,
      },
      resume: {
        normal:          normal.length,
        sous_avancement: sous_avancement.length,
        depasse:         depasse.length,
        total:           items.length,
      },
      normal,
      sous_avancement,
      depasse,
      items: result,
    });
  } catch (err) {
    res.status(502).json({ error: 'Erreur Baserow', detail: err.message });
  }
});

module.exports = router;
