import { fileStorageService } from "@/features/local/utils/fileStorageService";
import { trpcAppRouter } from "@/services/serverFunctions/appRouter";
import { createTrpcContext } from "@/services/serverFunctions/context";
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { createServerSideHelpers } from "@trpc/react-query/server";
import superjson from "superjson";

export default async function DataHydration({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  console.log("starting hydration");
  const trpcHelper = createServerSideHelpers({
    router: trpcAppRouter,
    ctx: createTrpcContext(),
    transformer: superjson,
    queryClientConfig: {
      defaultOptions: {
        queries: {
          staleTime: Infinity,
        },
      },
    },
  });

  const allSettings = await fileStorageService.settings.getAllCoursesSettings();

  await Promise.all(
    allSettings.map(async (settings) => {
      const courseName = settings.name;
      const moduleNames = await trpcHelper.module.getModuleNames.fetch({
        courseName,
      });
      await Promise.all([
        // assignments
        ...moduleNames.map(
          async (moduleName) =>
            await trpcHelper.assignment.getAllAssignments.prefetch({
              courseName,
              moduleName,
            })
        ),
        // quizzes
        ...moduleNames.map(
          async (moduleName) =>
            await trpcHelper.quiz.getAllQuizzes.prefetch({
              courseName,
              moduleName,
            })
        ),
        // pages
        ...moduleNames.map(
          async (moduleName) =>
            await trpcHelper.page.getAllPages.prefetch({
              courseName,
              moduleName,
            })
        ),
      ]);
    })
  );

  // lectures
  await Promise.all(
    allSettings.map(
      async (settings) =>
        await trpcHelper.lectures.getLectures.fetch({
          courseName: settings.name,
        })
    )
  );

  const dehydratedState = dehydrate(trpcHelper.queryClient);
  console.log("ran hydration");

  return (
    <HydrationBoundary state={dehydratedState}>{children}</HydrationBoundary>
  );
}
