import { useQuery } from "@tanstack/react-query";
import type { Agent } from "@paperclipai/shared";
import { agentsApi } from "../api/agents";
import { useCompany } from "../context/CompanyContext";

export function useBrainstormerDefault(): string | null {
  const { selectedCompanyId } = useCompany();

  const { data: agents = [] } = useQuery<Agent[]>({
    queryKey: ["agents", selectedCompanyId],
    queryFn: () => agentsApi.list(selectedCompanyId!),
    enabled: !!selectedCompanyId,
  });

  // Reuses same queryKey as ChatPanel's agent list — React Query deduplicates
  const generalAgent = agents
    .filter((a) => a.role === "general")
    .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())[0];

  return generalAgent?.id ?? null;
}
