import { createRoute } from "../../../modules/api-utils/createRoute";
import { procurement } from "../../../managers/procurement";
import { apiResponse } from "../../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../middleware/authorization";
import { processObjectValuePerms } from "../../../modules/permission-utils/processObjectPermissions";

/* /v1/procurement/items/:identifier */
export default createRoute(
  "get",
  ["/items/:identifier"],
  async (c) => {
    const identifier = c.req.param("identifier");
    const includeLinkedItems = c.req.query("includeLinkedItems") === "true";

    const item = await procurement.fetchItem(identifier);

    const gatedData = await processObjectValuePerms(
      item.toJson({ includeLinkedItems }),
      "obj.catalogItem",
      c.get("user"),
    );

    const response = apiResponse.successful(
      "Catalog item fetched successfully!",
      gatedData,
    );

    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["procurement.catalog.fetch"] }),
);
