/**
 * GET /api/alertes
 * Alertes délais : marchés dont la date de fin approche
 */
const express = require('express');
const router  = express.Router();
const { getMarches } = require('../services/baserow');
const {
  isCloture, getDelaiRestant, niveauAlerte, normalizeMarche,
  DELAI_ATTENTION,
} = require('../services/calc');

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

    let rows = await getMarches();

    // 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 (projet)       rows = rows.filter(r => String(r.projet || '').toLowerCase().includes(projet.toLowerCase()));

    // Uniquement marchés actifs avec alerte (délai ≤ DELAI_ATTENTION)
    const actifs = rows.filter(r => !isCloture(r));
    const alertes = actifs
      .map(r => ({ ...r, _delai: getDelaiRestant(r) }))
      .filter(r => r._delai !== null && r._delai <= DELAI_ATTENTION)
      .map(r => ({ ...normalizeMarche(r), delai_restant: r._delai, niveau: niveauAlerte(r._delai) }))
      .filter(r => !niveau || r.niveau === niveau)
      .sort((a, b) => a.delai_restant - b.delai_restant);

    res.json({
      count:    alertes.length,
      critique: alertes.filter(a => a.niveau === 'critique').length,
      attention: alertes.filter(a => a.niveau === 'attention').length,
      items:    alertes,
    });
  } catch (err) {
    res.status(502).json({ error: 'Erreur Baserow', detail: err.message });
  }
});

module.exports = router;
