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";

/* GET /v1/procurement/items/:identifier/linked */
export default createRoute(
  "get",
  ["/items/:identifier/linked"],
  async (c) => {
    const identifier = c.req.param("identifier");
    const item = await procurement.fetchItem(identifier);

    const linkedItems = item.getLinkedItems().map((linked) => linked.toJson());

    const gatedData = await Promise.all(
      linkedItems.map((linked) =>
        processObjectValuePerms(linked, "obj.catalogItem", c.get("user")),
      ),
    );

    const response = apiResponse.successful(
      "Linked catalog items fetched successfully!",
      gatedData,
    );

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