import { z, createRoute, OpenAPIHono } from "@hono/zod-openapi";
import jwt from "jsonwebtoken";
import type { CustomJwtPayload } from "../../../../types/jwtToken.js";
import { authMiddleware } from "../../middleware/authMiddleware.js";
import { roleCheck } from "../../controllers/userRoles/getUserAccess.js";

const { verify } = jwt;
const app = new OpenAPIHono();

const responseSchema = z.object({
  message: z.string().optional().openapi({ example: "User Created" }),
});

app.openapi(
  createRoute({
    tags: ["auth:user"],
    summary: "returns the users access",
    method: "get",
    path: "/getuseraccess",
    middleware: [authMiddleware],
    responses: {
      200: {
        content: { "application/json": { schema: responseSchema } },
        description: "Retrieve the user",
      },
    },
  }),
  async (c) => {
    // apit hit
    //apiHit(c, { endpoint: "api/auth/getUserRoles" });
    const authHeader = c.req.header("Authorization");
    const token = authHeader?.split("Bearer ")[1] || "";
    try {
      const secret = process.env.JWT_SECRET!;
      if (!secret) {
        throw new Error("JWT_SECRET is not defined in environment variables");
      }

      const payload = verify(token, secret) as CustomJwtPayload;

      const canAccess = await roleCheck(payload.user?.user_id);

      return c.json(
        {
          sucess: true,
          message: `User ${payload.user?.username} can access`,
          data: canAccess,
        },
        200
      );
    } catch (error) {
      console.log(error);
    }

    return c.json({ message: "UserRoles coming over" });
  }
);

export default app;
