import { TRPCError } from "@trpc/server";
import { t } from "@/lib/trpc";
import { OnboardService } from "@/services/onboard";

export const onboardMiddleware = t.middleware(async ({ ctx, next }) => {
	if (!ctx.serviceContainer) {
		throw new TRPCError({
			code: "INTERNAL_SERVER_ERROR",
			message: "Service container not available",
		});
	}

	const onboardService = ctx.serviceContainer.get(OnboardService);

	if (!onboardService.getNeedsOnboarding()) {
		throw new TRPCError({
			code: "FORBIDDEN",
			message: "Onboarding is not needed - server is already set up",
		});
	}

	return next({
		ctx: {
			...ctx,
			onboardService,
		},
	});
});
