import { ContentfulStatusCode } from "hono/utils/http-status";
import { apiResponse } from "../../modules/api-utils/apiResponse";
import { createRoute } from "../../modules/api-utils/createRoute";
import { authMiddleware } from "../middleware/authorization";
import { users } from "../../managers/users";
import GenericError from "../../Errors/GenericError";
import { processObjectValuePerms } from "../../modules/permission-utils/processObjectPermissions";

/* GET /v1/user/users/:identifier/roles */
export default createRoute(
  "get",
  ["/users/:identifier/roles"],

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

    const user = await users.fetchUser({ id: identifier });
    if (!user)
      throw new GenericError({
        name: "UserNotFound",
        message: `User with identifier '${identifier}' was not found.`,
        status: 404,
      });

    const roles = await user.fetchRoles();

    const gatedData = await Promise.all(
      roles.map((r) =>
        processObjectValuePerms(
          r.toJson({ viewPermissions: true }),
          "obj.role",
          c.get("user"),
        ),
      ),
    );

    const response = apiResponse.successful(
      "User Roles Fetched Successfully!",
      gatedData,
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["user.read.other", "role.read"] }),
);
