import { Router } from "express";

import { authenticate, authorize } from "../../middleware/auth.js";
import { validate } from "../../middleware/validate.js";
import { asyncHandler } from "../../utils/http.js";
import { createItem, deleteItem, listItems, updateItem } from "./items.service.js";
import { itemBodySchema, itemParamsSchema, itemPatchSchema, itemQuerySchema } from "./items.schemas.js";

export const itemsRouter = Router();

itemsRouter.get(
  "/",
  authenticate,
  validate({ query: itemQuerySchema }),
  asyncHandler(async (request, response) => {
    const data = await listItems({
      categoryId: request.query.categoryId as string | undefined,
      status: request.query.status as "all" | "active" | "service" | "retired" | undefined,
      search: request.query.search as string | undefined,
      includeInactive: request.query.includeInactive as boolean | undefined
    });

    response.json({ data });
  })
);

itemsRouter.post(
  "/",
  authenticate,
  authorize("admin", "operator"),
  validate({ body: itemBodySchema }),
  asyncHandler(async (request, response) => {
    const created = await createItem(request.body);
    response.status(201).json({ data: created });
  })
);

itemsRouter.patch(
  "/:id",
  authenticate,
  authorize("admin", "operator"),
  validate({ params: itemParamsSchema, body: itemPatchSchema }),
  asyncHandler(async (request, response) => {
    const updated = await updateItem(request.params.id as string, request.body);
    response.json({ data: updated });
  })
);

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