import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { adminFetch } from './admin-api';

// ── Types ──────────────────────────────────────────────────────────────

export interface SensitiveKeysConfig {
  keys: string[];
}

export interface SensitiveKeysResponse {
  keys: string[];
  pushResult: {
    success: boolean;
    total: number;
    responded: number;
    responses: { agentId: string; status: string; message: string | null }[];
    timedOut: string[];
  } | null;
}

// ── Query Hooks ────────────────────────────────────────────────────────

export function useSensitiveKeys() {
  return useQuery({
    queryKey: ['admin', 'sensitive-keys'],
    queryFn: () => adminFetch<SensitiveKeysConfig | null>('/sensitive-keys'),
  });
}

// ── Mutation Hooks ─────────────────────────────────────────────────────

export function useUpdateSensitiveKeys() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ keys, pushToAgents }: { keys: string[]; pushToAgents: boolean }) =>
      adminFetch<SensitiveKeysResponse>(`/sensitive-keys?pushToAgents=${pushToAgents}`, {
        method: 'PUT',
        body: JSON.stringify({ keys }),
      }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['admin', 'sensitive-keys'] });
    },
  });
}
