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

/* /v1/procurement/filters */
export default createRoute(
  "get",
  ["/filters"],
  async (c) => {
    const category = c.req.query("category") as string | undefined;
    const subcategory = c.req.query("subcategory") as string | undefined;
    const includeInactive = c.req.query("includeInactive") === "true";

    const filterOpts = { category, subcategory, includeInactive };

    const [categories, subcategories, manufacturers] = await Promise.all([
      procurement.fetchDistinctValues("category", filterOpts),
      procurement.fetchDistinctValues("subcategory", filterOpts),
      procurement.fetchDistinctValues("manufacturer", filterOpts),
    ]);

    const response = apiResponse.successful(
      "Available filter values fetched successfully!",
      { categories, subcategories, manufacturers },
    );

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