import {
  fetchDashboardUrl,
  fetchListOfParameters,
  fetchListOfPermittedDashboards,
} from "@/record-management/services/api/advancedDashboardService";
import { useQuery } from "@tanstack/react-query";

export const useAdvancedDashboardHook = (
  id?: string,
  body?: Record<string, any>
) => {
  // 1️⃣ Fetch list of permitted dashboards
  const permittedDashboardsQuery = useQuery({
    queryKey: ["permittedDashboards"],
    queryFn: fetchListOfPermittedDashboards,
    staleTime: 5 * 60 * 1000, // 5 minutes cache
  });

  // 2️⃣ Fetch specific dashboard iframe URL (only runs if id exists)
  const dashboardUrlQuery = useQuery({
    queryKey: ["dashboardUrl", id],
    queryFn: () => fetchDashboardUrl({ params: body }, id!),
    enabled: !!id, // only run when `id` is defined
  });
  const dashboardParameter = useQuery({
    queryKey: ["dashboardParameter", id],
    queryFn: () => fetchListOfParameters(id as string),
    enabled: !!id,
  });

  return {
    permittedDashboards: permittedDashboardsQuery.data,
    isLoadingPermitted: permittedDashboardsQuery.isLoading,
    isErrorPermitted: permittedDashboardsQuery.isError,

    dashboardUrl: dashboardUrlQuery.data,
    isLoadingUrl: dashboardUrlQuery.isLoading,
    isErrorUrl: dashboardUrlQuery.isError,
    dashboardParameter: dashboardParameter.data,
  };
};
