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

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

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

    const data = schema.parse(body);

    const role = await roles.create(data);

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