import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  modelProvidersApi,
  type CreateProviderPayload,
  type ModelDefaults,
} from "../lib/api/modelProviders";

const providersKey = (capability?: string) =>
  capability ? ["model-providers", capability] : ["model-providers"];
const defaultsKey = () => ["model-defaults"];

export function useModelProviders(capability?: string) {
  return useQuery({
    queryKey: providersKey(capability),
    queryFn: () => modelProvidersApi.list(capability),
    staleTime: 30_000,
  });
}

export function useCreateProvider() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (payload: CreateProviderPayload) => modelProvidersApi.create(payload),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["model-providers"] }),
  });
}

export function useUpdateProvider() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, patch }: { id: number; patch: Partial<CreateProviderPayload> }) =>
      modelProvidersApi.update(id, patch),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["model-providers"] }),
  });
}

export function useDeleteProvider() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => modelProvidersApi.delete(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["model-providers"] }),
  });
}

export function useModelDefaults() {
  return useQuery({
    queryKey: defaultsKey(),
    queryFn: modelProvidersApi.getDefaults,
    staleTime: 30_000,
  });
}

export function useSaveModelDefaults() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (defaults: ModelDefaults) => modelProvidersApi.saveDefaults(defaults),
    onSuccess: () => qc.invalidateQueries({ queryKey: defaultsKey() }),
  });
}
