import { Request, Response } from 'express';
import { AppError } from '../errors/app-error';
import { listerCatalogue } from '../services/materiel.service';
import { toMaterielResponse } from '../dtos/materiel.dto';

function parseCategorieId(value: unknown): number | undefined {
  if (value === undefined) {
    return undefined;
  }

  const parsed = Number(value);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    throw new AppError(400, 'categorieId invalide');
  }

  return parsed;
}

export async function getCatalogue(req: Request, res: Response): Promise<void> {
  const user = req.user;
  if (!user) {
    throw new AppError(401, 'Authentification requise');
  }

  const recherche = typeof req.query.q === 'string' ? req.query.q : undefined;
  const categorieId = parseCategorieId(req.query.categorieId);

  const materiels = await listerCatalogue(user.campusId, { categorieId, recherche });
  res.json({ data: materiels.map(toMaterielResponse) });
}
