import { Request, Response } from 'express';
import { AppError } from '../errors/app-error';
import { listerCatalogue, obtenirDetailMateriel } from '../services/materiel.service';
import { toMaterielDetailResponse, 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;
}

function parseId(value: unknown): number {
  if (typeof value !== 'string') {
    throw new AppError(400, 'id invalide');
  }

  const parsed = Number(value);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    throw new AppError(400, 'id 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) });
}

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

  const materiel = await obtenirDetailMateriel(parseId(req.params.id), user.campusId);
  res.json({ data: toMaterielDetailResponse(materiel) });
}
