import { Router } from "express";
import { body, param, query } from "express-validator";

import { companiesController } from "../controllers/companiesController.js";
import { handleValidation } from "../middleware/validation.js";
import { asyncHandler } from "../utils/asyncHandler.js";

const router = Router();

router.get(
  "/",
  [
    query("search").optional().isString().withMessage("La recherche est invalide."),
    handleValidation,
  ],
  asyncHandler(companiesController.list),
);

router.get(
  "/:id",
  [
    param("id").isInt({ min: 1 }).withMessage("Identifiant société invalide."),
    handleValidation,
  ],
  asyncHandler(companiesController.getById),
);

router.post(
  "/",
  [
    body("name")
      .trim()
      .isLength({ min: 1, max: 255 })
      .withMessage("Le nom de la société est obligatoire."),
    body("nif")
      .trim()
      .isLength({ min: 1, max: 32 })
      .withMessage("Le NIF est obligatoire."),
    body("rc")
      .trim()
      .isLength({ min: 1, max: 64 })
      .withMessage("Le RC est obligatoire."),
    body("email")
      .optional({ values: "falsy" })
      .isEmail()
      .withMessage("L'adresse e-mail est invalide."),
    body("currency")
      .optional({ values: "falsy" })
      .isLength({ min: 3, max: 10 })
      .withMessage("La devise est invalide."),
    body("fiscal_year_start_month")
      .optional()
      .isInt({ min: 1, max: 12 })
      .withMessage("Le mois de démarrage de l'exercice est invalide."),
    handleValidation,
  ],
  asyncHandler(companiesController.create),
);

export default router;
