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 { z } from "zod";

/* POST /v1/role/:identifier/permissions */
export default createRoute(
  "post",
  ["/:identifier/permissions"],

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

    const schema = z.object({
      permissions: z
        .array(z.string().min(1, "Permission node cannot be empty"))
        .min(1, "At least one permission is required"),
    });

    const data = schema.parse(body);

    const role = await roles.fetch(identifier);
    await role.addPermissions(...data.permissions);

    const response = apiResponse.successful(
      "Permissions Added Successfully!",
      role.toJson({ viewPermissions: true }),
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["role.update"] }),
);
