import {
  useMutation,
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";
import * as machinesApi from "../../api/machines";
import type { DeleteMachineParams } from "../../api/types";

const MACHINES_KEY = ["machines"] as const;

/** List all machines. Polls so online/offline status stays fresh. */
export function useMachines() {
  return useQuery({
    queryKey: MACHINES_KEY,
    queryFn: ({ signal }) => machinesApi.listMachines(signal),
    refetchInterval: 20_000,
    staleTime: 10_000,
  });
}

/** Machine history (sessions + events) for the detail drawer. Lazy via `enabled`. */
export function useMachineHistory(agentId: string | null) {
  return useQuery({
    queryKey: ["machine-history", agentId],
    queryFn: ({ signal }) => machinesApi.getMachineHistory(agentId!, signal),
    enabled: agentId != null,
    staleTime: 30_000,
  });
}

/** Delete a machine, then invalidate the list so it disappears. */
export function useDeleteMachine() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({
      agentId,
      params,
    }: {
      agentId: string;
      params: DeleteMachineParams;
    }) => machinesApi.deleteMachine(agentId, params),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: MACHINES_KEY });
    },
  });
}

// --- Admin: per-agent keys --------------------------------------------------

export function useMachineKeys(agentId: string | null, enabled: boolean) {
  return useQuery({
    queryKey: ["machine-keys", agentId],
    queryFn: () => machinesApi.listMachineKeys(agentId!),
    enabled: enabled && agentId != null,
    staleTime: 15_000,
  });
}

export function useCreateMachineKey(agentId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: () => machinesApi.createMachineKey(agentId),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ["machine-keys", agentId] });
    },
  });
}

export function useRevokeMachineKey(agentId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (keyId: string) =>
      machinesApi.revokeMachineKey(agentId, keyId),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ["machine-keys", agentId] });
    },
  });
}
