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

  async (c) => {
    const allCredentialTypes = await credentialTypes.fetchAll();

    const gatedData = await Promise.all(
      allCredentialTypes.map((ct) =>
        processObjectValuePerms(
          ct.toJson({ includeCredentialCount: true }),
          "obj.credentialType",
          c.get("user"),
        ),
      ),
    );

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