import { TRPCError } from "@trpc/server";
import auth from "@/lib/auth";
import { t } from "@/lib/trpc";

export function createPermissionMiddleware(
	resource: string,
	actions: string[],
) {
	return t.middleware(async ({ ctx, next }) => {
		const session = await auth.api.getSession({
			headers: ctx.requestContext.req.raw.headers,
		});

		if (!session) {
			throw new TRPCError({
				code: "UNAUTHORIZED",
				message: "Authentication required. Please log in to continue.",
			});
		}

		const hasPermission = await auth.api.userHasPermission({
			body: {
				userId: session.user.id,
				permissions: {
					[resource]: actions,
				},
			},
		});

		if (!hasPermission) {
			throw new TRPCError({
				code: "FORBIDDEN",
				message: `You do not have permission to perform this action on ${resource}.`,
			});
		}

		return next({ ctx: { ...ctx, userSession: session } });
	});
}

export const createAdminMiddleware = () => {
	return t.middleware(async ({ ctx, next }) => {
		const session = await auth.api.getSession({
			headers: ctx.requestContext.req.raw.headers,
		});

		if (!session) {
			throw new TRPCError({
				code: "UNAUTHORIZED",
				message: "Authentication required. Please log in to continue.",
			});
		}

		const hasAdminPermission = await auth.api.userHasPermission({
			body: {
				userId: session.user.id,
				permissions: {
					libraries: ["create", "update", "delete"],
				},
			},
		});

		if (!hasAdminPermission) {
			throw new TRPCError({
				code: "FORBIDDEN",
				message: "Admin privileges required for this action.",
			});
		}

		return next({ ctx: { ...ctx, userSession: session } });
	});
};
