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

export const dashboardMiddleware = 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: {
				dashboard: ["access"],
			},
		},
	});

	if (!hasPermission) {
		throw new TRPCError({
			code: "FORBIDDEN",
			message: "You do not have permission to access the dashboard.",
		});
	}

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