import { cookies } from "next/headers";
import {
  dehydrate,
  HydrationBoundary,
  QueryClient,
} from "@tanstack/react-query";
import { isAuthenticatedToken } from "@/lib/entry-route-cache";
import { fetchProfileSSR } from "@/lib/ssr-fetch";
import { marriageQueryKeys } from "@/hooks/marriage/query-keys";
import QuestionsListClient from "./questions-list-client";

export const dynamic = "force-dynamic";

/**
 * Server Component wrapper for questions-list.
 *
 * Prefetches the marriage profile server-side using the HABIB_TOKEN cookie
 * (Flutter sets it via WebViewCookieManager before loadRequest). The profile
 * determines which page the user should see — having it in the HTML avoids
 * the white-flash caused by waiting for the client-side API call.
 *
 * The sections/form-overview loads client-side with shimmer — that's fine.
 */
export default async function QuestionsListPage() {
  const cookieStore = await cookies();

  const token =
    cookieStore.get("HABIB_TOKEN")?.value ??
    cookieStore.get("habib_token")?.value;

  const queryClient = new QueryClient({
    defaultOptions: {
      queries: { staleTime: 10 * 1000 },
    },
  });

  if (isAuthenticatedToken(token)) {
    await queryClient.prefetchQuery({
      queryKey: marriageQueryKeys.profile(),
      queryFn: () => fetchProfileSSR(token!),
    });
  }

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <QuestionsListClient />
    </HydrationBoundary>
  );
}
