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

  async (c) => {
    const allRoles = await roles.fetchAllRoles();

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

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