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

/**
 * Resolves the active investisseur from the X-Investisseur-Id header (or query),
 * verifies it belongs to the authenticated user, and exposes it as req.investisseur.
 *
 * Routes that operate on investisseur-scoped data must use this middleware.
 */
export function requireInvestisseur(req, res, next) {
  const raw = req.header('X-Investisseur-Id') || req.query.investisseurId;
  const id = Number(raw);
  if (!id) throw new HttpError(400, 'Missing investisseur id (header X-Investisseur-Id)');

  const row = db
    .prepare('SELECT id, nom, type_fiscal FROM investisseurs WHERE id = ? AND user_id = ?')
    .get(id, req.user.id);

  if (!row) throw new HttpError(403, 'Investisseur not found or not owned by user');
  req.investisseur = row;
  next();
}
