import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiFetch } from "./client";
import type { CreateProviderRequest, ProviderConfig, ProviderStatus } from "@/types/api";

// ─── Circuit breaker status (legacy, still used by overview) ──────────────────

export function useProviderStatuses() {
  return useQuery({
    queryKey: ["providers", "status"],
    queryFn: () => apiFetch<ProviderStatus[]>("/v1/admin/providers/status"),
    refetchInterval: 15_000,
  });
}

// ─── Provider config CRUD ─────────────────────────────────────────────────────

export function useProviderConfigs() {
  return useQuery({
    queryKey: ["providers", "configs"],
    queryFn: async () => {
      const res = await apiFetch<{ data: ProviderConfig[] }>("/v1/admin/providers");
      return res.data ?? [];
    },
    refetchInterval: 30_000,
  });
}

export function useCreateProvider() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: CreateProviderRequest) =>
      apiFetch<ProviderConfig>("/v1/admin/providers", {
        method: "POST",
        body: JSON.stringify(data),
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["providers"] }),
  });
}

export function useUpdateProvider() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: CreateProviderRequest }) =>
      apiFetch<ProviderConfig>(`/v1/admin/providers/${id}`, {
        method: "PUT",
        body: JSON.stringify(data),
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["providers"] }),
  });
}

export function useDeleteProvider() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiFetch<void>(`/v1/admin/providers/${id}`, { method: "DELETE" }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["providers"] }),
  });
}

export function useTestProvider() {
  return useMutation({
    mutationFn: (id: string) =>
      apiFetch<{ healthy: boolean; error?: string }>(`/v1/admin/providers/${id}/test`, {
        method: "POST",
      }),
  });
}
