import { Router } from "express";

import { authorize, authenticate } from "../../middleware/auth.js";
import { validate } from "../../middleware/validate.js";
import { asyncHandler } from "../../utils/http.js";
import { categoryBodySchema, categoryParamsSchema } from "./categories.schemas.js";
import { createCategory, deleteCategory, listCategories, updateCategory } from "./categories.service.js";

export const categoriesRouter = Router();

categoriesRouter.get(
  "/",
  authenticate,
  asyncHandler(async (_request, response) => {
    response.json({ data: await listCategories() });
  })
);

categoriesRouter.post(
  "/",
  authenticate,
  authorize("admin"),
  validate({ body: categoryBodySchema }),
  asyncHandler(async (request, response) => {
    const created = await createCategory(request.body.name);
    response.status(201).json({ data: created });
  })
);

categoriesRouter.patch(
  "/:id",
  authenticate,
  authorize("admin"),
  validate({ params: categoryParamsSchema, body: categoryBodySchema }),
  asyncHandler(async (request, response) => {
    const updated = await updateCategory(request.params.id as string, request.body.name);
    response.json({ data: updated });
  })
);

categoriesRouter.delete(
  "/:id",
  authenticate,
  authorize("admin"),
  validate({ params: categoryParamsSchema }),
  asyncHandler(async (request, response) => {
    await deleteCategory(request.params.id as string);
    response.status(204).send();
  })
);
