import { Hono } from "hono/tiny";
import { createRoute } from "../../modules/api-utils/createRoute";
import { credentials } from "../../managers/credentials";
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/credential/company/:companyId */
export default createRoute(
  "get",
  ["/credentials/company/:companyId"],

  async (c) => {
    const companyCredentials = await credentials.fetchByCompany(
      c.req.param("companyId"),
    );

    const gatedData = await Promise.all(
      companyCredentials.map((cred) =>
        processObjectValuePerms(cred.toJson(), "obj.credential", c.get("user")),
      ),
    );

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