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";

/* GET /v1/credential/credentials/:id/sub-credentials */
export default createRoute(
  "get",
  ["/credentials/:id/sub-credentials"],

  async (c) => {
    const parentId = c.req.param("id");

    // Verify the parent credential exists
    await credentials.fetch(parentId);

    const subCredentials = await credentials.fetchSubCredentials(parentId);

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

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