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

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

    const role = await roles.fetch(identifier);
    const users = role.getUsers();

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

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