import { Request, Response } from 'express';
import { AppError } from '../errors/app-error';
import {
  creerEmprunt,
  listerMesEmpruntsEnCours,
  restituerEmprunt,
} from '../services/emprunt.service';
import {
  parseCreerEmpruntRequest,
  parseRestituerEmpruntRequest,
  toEmpruntResponse,
} from '../dtos/emprunt.dto';

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

  const emprunts = await listerMesEmpruntsEnCours(user.id);
  res.json({ data: emprunts.map(toEmpruntResponse) });
}

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

  const request = parseCreerEmpruntRequest(req.body);
  const emprunt = await creerEmprunt(user.id, user.campusId, request);
  res.status(201).json({ data: toEmpruntResponse(emprunt) });
}

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

  const empruntId = Number(req.params.id);
  if (!Number.isInteger(empruntId) || empruntId <= 0) {
    throw new AppError(400, 'Identifiant emprunt invalide');
  }

  const request = parseRestituerEmpruntRequest(req.body);
  const emprunt = await restituerEmprunt(user.id, empruntId, request);
  res.json({ data: toEmpruntResponse(emprunt) });
}
