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

export const authenticationMiddleware = 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.",
		});
	}

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