import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import axios from "axios";
import jwt from "jsonwebtoken";
import type { CustomJwtPayload } from "../../../../types/jwtToken.js";
import { roleCheck } from "../../controllers/userRoles/getUserAccess.js";
import { authMiddleware } from "../../middleware/authMiddleware.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: any) => {
		// apit hit
		//apiHit(c, { endpoint: "api/auth/getUserRoles" });
		const authHeader = c.req.header("Authorization");

		const user = c.get("user");

		if (!user) {
			return c.json(
				{
					success: true,
					message: `Unauthorized`,
				},
				401,
			);
		}
		try {
			const cookieHeader = c.req.header("Cookie");
			if (!cookieHeader) return c.json({ error: "Unauthorized" }, 401);

			const res = await axios.get(
				`${process.env.LST_BASE_URL}/api/user/roles`,
				{
					headers: { Cookie: cookieHeader },
				},
			);

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

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

export default app;
