import { ContentfulStatusCode } from "hono/utils/http-status";
import { z } from "zod";
import { apiResponse } from "../../../modules/api-utils/apiResponse";
import { createRoute } from "../../../modules/api-utils/createRoute";
import { authMiddleware } from "../../middleware/authorization";

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

// /v1/user/@me/check-permission
export default createRoute(
  "post",
  ["/@me/check-permission"],
  async (c) => {
    const user = c.get("user");

    const body = await c.req.json();
    const { permissions } = checkPermissionSchema.parse(body);

    const results = await Promise.all(
      permissions.map(async (permission) => ({
        permission,
        hasPermission: await user.hasPermission(permission),
      })),
    );

    const response = apiResponse.successful("Permission check completed.", {
      results,
    });

    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ scopes: ["user.read"] }),
);
