import { createServerSideHelpers } from "@trpc/react-query/server";
import superjson from "superjson";
import { appRouter } from "~/server/api/root";
import type { Session } from "~/server/api/trpc";
import { verifyToken } from "~/server/auth/jwt";

export const generateSSGHelper = () =>
	createServerSideHelpers({
		ctx: { session: null, sessionStatus: "NO_SESSION" },
		router: appRouter,
		transformer: superjson, // optional - adds superjson serialization
	});

const generateHelperWSession = (session: Session) =>
	createServerSideHelpers({
		ctx: { session: session, sessionStatus: "AUTHENTICATED" },
		router: appRouter,
		transformer: superjson, // optional - adds superjson serialization
	});

export const TrpcAuthedFetchingIstance = async ({
	access_token,
}: {
	access_token: string | undefined;
}) => {
	if (access_token) {
		const { expired, session } = await verifyToken(access_token);

		if (!expired && session) {
			const trpc = generateHelperWSession(session);

			return { session, trpc };
		}
		return null;
	}

	return null;
};
