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

/* PATCH /v1/role/:identifier */
export default createRoute(
  "patch",
  ["/:identifier"],

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

    const schema = z
      .object({
        title: z.string().min(1, "Title cannot be empty"),
        moniker: z.string().min(1, "Moniker cannot be empty"),
        permissions: z.array(
          z.string().min(1, "Permission node cannot be empty"),
        ),
      })
      .partial()
      .strict();

    const data = schema.parse(body);

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

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