import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { companies } from "../../managers/companies";
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/company/companies */
export default createRoute(
  "get",
  ["/companies"],
  async (c) => {
    const page = new Number(c.req.query("page") ?? 1) as number;
    const rpp = new Number(c.req.query("rpp") ?? 30) as number; // Records Per Page
    const search = c.req.query("search") as string;

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

    const companyQty = search
      ? (await companies.search(search, 1, 999999)).length
      : await companies.count();

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

    let response = apiResponse.successful(
      "Companies Fetched Successfully!",
      gatedData,
      {
        pagination: {
          previousPage: page == 1 ? null : page - 1, // Previous Page
          currentPage: page, // Current Page
          nextPage: page >= companyQty / rpp ? null : page + 1, // Next Page
          totalPages: Math.ceil(companyQty / rpp), // Total Number of Pages
          totalRecords: companyQty, // Total Number of Records
          listedRecords: rpp, // Total Number of Records being recieved at time of request.
        },
      },
    );

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