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({
    router: appRouter,
    ctx: { session: null },
    transformer: superjson, // optional - adds superjson serialization
  });

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

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

    if (session) {
      const trpc = generateHelperWSession(session);

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

  return null;
};
