import { Router } from 'express';
import db from '../db/index.js';
import { HttpError } from '../middleware/errorHandler.js';

const router = Router();
// Monté sous requireAuth (sans requireAdmin) — lecture seule pour tous les users

function attachCats(rows) {
  if (rows.length === 0) return rows;
  const ids = rows.map(r => r.id);
  const cats = db.prepare(`
    SELECT rc.referentiel_id, rc.categorie_nom
    FROM referentiel_categories rc
    WHERE rc.referentiel_id IN (${ids.map(() => '?').join(',')})
    ORDER BY rc.categorie_nom
  `).all(...ids);
  const map = {};
  for (const c of cats) {
    if (!map[c.referentiel_id]) map[c.referentiel_id] = [];
    map[c.referentiel_id].push(c.categorie_nom);
  }
  return rows.map(r => ({ ...r, categories: map[r.id] || [] }));
}

function attachNotation(rows) {
  if (rows.length === 0) return rows;
  const ids = rows.map(r => r.id);
  const notations = db.prepare(`
    SELECT * FROM referentiel_notation
    WHERE referentiel_id IN (${ids.map(() => '?').join(',')})
    ORDER BY referentiel_id, ordre, id
  `).all(...ids);
  const map = {};
  for (const n of notations) {
    if (!map[n.referentiel_id]) map[n.referentiel_id] = [];
    map[n.referentiel_id].push({ ...n, valeurs: n.valeurs ? JSON.parse(n.valeurs) : null });
  }
  return rows.map(r => ({ ...r, notation: map[r.id] || [] }));
}

function parsePaysOp(rows) {
  return rows.map(r => ({
    ...r,
    pays_operation: r.pays_operation
      ? (typeof r.pays_operation === 'string' ? JSON.parse(r.pays_operation) : r.pays_operation)
      : [],
  }));
}

// ── GET /api/referentiel-public/:id ───────────────────────────────────────────
router.get('/:id', (req, res, next) => {
  try {
    const row = db.prepare('SELECT * FROM plateformes_referentiel WHERE id = ?').get(req.params.id);
    if (!row) throw new HttpError(404, 'Référentiel introuvable');
    const [enriched] = parsePaysOp(attachNotation(attachCats([row])));
    res.json(enriched);
  } catch (e) { next(e); }
});

export default router;
