import type { NextFunction, Request, Response } from "express";
import { auth } from "../utils/auth.utils.js";

type PermissionMap = Record<string, string[]>;

declare global {
	namespace Express {
		interface Request {
			authz?: {
				success: boolean;
				permissions: PermissionMap;
			};
		}
	}
}

function normalizeRoles(roles: unknown): string {
	if (Array.isArray(roles)) return roles.join(",");
	if (typeof roles === "string") return roles;
	return "";
}

export function requirePermission(permissions: PermissionMap) {
	return async (req: Request, res: Response, next: NextFunction) => {
		try {
			const role = normalizeRoles(req.user?.roles) as any;

			const result = await auth.api.userHasPermission({
				body: {
					role,
					permissions,
				},
			});

			req.authz = {
				success: !!result?.success,
				permissions,
			};

			if (!result?.success) {
				return res.status(403).json({
					ok: false,
					message: "You do not have permission to perform this action.",
				});
			}

			next();
		} catch (error) {
			next(error);
		}
	};
}
