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

  async (c) => {
    const credentialType = await credentialTypes.fetch(c.req.param("id"));
    const credentials = await credentialType.fetchCredentials();

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

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