import { createRoute } from "../../modules/api-utils/createRoute";
import { procurement, CatalogFilterOpts } 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 */
export default createRoute(
  "get",
  ["/items"],
  async (c) => {
    const page = Number(c.req.query("page") ?? 1);
    const rpp = Number(c.req.query("rpp") ?? 30);
    const search = c.req.query("search") as string;
    const includeInactive = c.req.query("includeInactive") === "true";

    // Category / filter params
    const category = c.req.query("category") as string | undefined;
    const subcategory = c.req.query("subcategory") as string | undefined;
    const group = c.req.query("group") as string | undefined;
    const manufacturer = c.req.query("manufacturer") as string | undefined;
    const ecosystem = c.req.query("ecosystem") as string | undefined;
    const inStock = c.req.query("inStock") === "true" ? true : undefined;
    const minPrice = c.req.query("minPrice")
      ? Number(c.req.query("minPrice"))
      : undefined;
    const maxPrice = c.req.query("maxPrice")
      ? Number(c.req.query("maxPrice"))
      : undefined;

    const filterOpts: CatalogFilterOpts = {
      includeInactive,
      category,
      subcategory,
      group,
      manufacturer,
      ecosystem,
      inStock,
      minPrice,
      maxPrice,
    };

    const data = search
      ? await procurement.search(search, page, rpp, filterOpts)
      : await procurement.fetchPages(page, rpp, filterOpts);

    const totalRecords = search
      ? await procurement.countSearch(search, filterOpts)
      : await procurement.count(filterOpts);

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

    const response = apiResponse.successful(
      "Catalog items fetched successfully!",
      gatedData,
      {
        pagination: {
          previousPage: page <= 1 ? null : page - 1,
          currentPage: page,
          nextPage: page >= totalRecords / rpp ? null : page + 1,
          totalPages: Math.ceil(totalRecords / rpp),
          totalRecords,
          listedRecords: rpp,
        },
      },
    );

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