"use client";

import { useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";

import categoryApi from "@/shared/services/category";
import classificationApi from "@/shared/services/classification";
import mapProjectionSystemApi from "@/shared/services/map-projection-system";
import organizationApi from "@/shared/services/organization";
import mapSourceApi from "@/shared/services/map-source";
import { useAuthSession } from "@/shared/hooks/use-session";

/**
 * Prefetches admin reference data (options) once the user session is ready.
 * This ensures select options are available before opening edit/add forms,
 * so forms can immediately display selected values.
 */
export default function RefDataBootstrap() {
  const qc = useQueryClient();
  const { isAuthenticated } = useAuthSession();

  useEffect(() => {
    if (!isAuthenticated) return;

    const staleTime = 5 * 60 * 1000; // 5 minutes

    qc.prefetchQuery({
      queryKey: ["projectionSystems"],
      queryFn: () => mapProjectionSystemApi.getMapProjectionSystems(),
      staleTime,
    });
    qc.prefetchQuery({
      queryKey: ["categories"],
      queryFn: () => categoryApi.getCategories(),
      staleTime,
    });
    qc.prefetchQuery({
      queryKey: ["classifications"],
      queryFn: () => classificationApi.getClassifications(),
      staleTime,
    });
    qc.prefetchQuery({
      queryKey: ["organizations"],
      queryFn: () => organizationApi.getOrganizations(),
      staleTime,
    });
    qc.prefetchQuery({
      queryKey: ["map-sources"],
      queryFn: () => mapSourceApi.getMapSources(),
      staleTime,
    });
  }, [qc, isAuthenticated]);

  return null;
}
