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/[id] */
export default createRoute(
  "get",
  ["/companies/:identifier"],

  async (c) => {
    const company = await companies.fetch(c.req.param("identifier"));
    const user = c.get("user");
    const includeAddress =
      c.req.query("includeAddress") === "true" &&
      !!user &&
      (await user.hasPermission("company.fetch.address"));
    const includePrimaryContact =
      c.req.query("includePrimaryContact") === "true";
    const includeAllContacts =
      c.req.query("includeAllContacts") === "true" &&
      !!user &&
      (await user.hasPermission("company.fetch.contacts"));

    const companyData = company.toJson({
      includeAddress,
      includePrimaryContact,
      includeAllContacts,
    });
    const gatedData = await processObjectValuePerms(
      companyData,
      "obj.company",
      c.get("user"),
    );

    // cw_Data fields were already gated by the explicit permission checks above
    // (company.fetch.contacts / company.fetch.address). Re-attach them so they
    // are not silently dropped by field-level gating on obj.company.cw_Data.
    if (companyData.cw_Data && Object.keys(companyData.cw_Data).length > 0) {
      (gatedData as any).cw_Data = companyData.cw_Data;
    }

    const response = apiResponse.successful(
      "Company Fetched Successfully!",
      gatedData,
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["company.fetch"] }),
);
