/**
 * GET /api/clotures
 * Marchés clôturés
 */
const express = require('express');
const router  = express.Router();
const { getMarches } = require('../services/baserow');
const { isCloture, normalizeMarche, parseNum, formatMontant } = require('../services/calc');

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

    let rows = await getMarches();

    // Uniquement clôturés
    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 (projet)       rows = rows.filter(r => String(r.projet || '').toLowerCase().includes(projet.toLowerCase()));
    if (nature)       rows = rows.filter(r => String(r.nature || '').toLowerCase().includes(nature.toLowerCase()));

    const items = rows.map(normalizeMarche);

    const totalBudget = rows.reduce((s, r) => s + parseNum(r.tot_marche ?? r.totmarche ?? r.montant), 0);

    // Par région
    const parRegion = {};
    for (const r of rows) {
      const reg = r.region || 'Inconnu';
      parRegion[reg] = (parRegion[reg] || 0) + 1;
    }

    res.json({
      count:   items.length,
      budget_total: formatMontant(totalBudget),
      budget_total_raw: totalBudget,
      par_region: parRegion,
      items,
    });
  } catch (err) {
    res.status(502).json({ error: 'Erreur Baserow', detail: err.message });
  }
});

module.exports = router;
