import { useEffect } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useAtom } from "jotai";
import { ipc, type Connector } from "@/ipc/types";
import { queryKeys } from "@/lib/queryKeys";
import { selectedConnectorIdAtom } from "@/atoms/appAtoms";

export function useLoadConnector(connectorId: number | null) {
  const [, setSelectedConnectorId] = useAtom(selectedConnectorIdAtom);
  const queryClient = useQueryClient();

  const { data, isLoading, error, refetch } = useQuery<Connector>({
    queryKey: queryKeys.connectors.detail({ connectorId }),
    queryFn: async () =>
      ipc.connector.getConnector({ connectorId: connectorId ?? -1 }),
    enabled: connectorId !== null,
  });

  useEffect(() => {
    setSelectedConnectorId(connectorId);
  }, [connectorId, setSelectedConnectorId]);

  const refreshConnector = async () => {
    await refetch();
    await queryClient.invalidateQueries({ queryKey: queryKeys.connectors.all });
  };

  return {
    connector: data ?? null,
    loading: isLoading,
    error: error ?? null,
    refreshConnector,
  };
}
