import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { configsApi } from '../api/configs.api';
import { useToast } from '@/lib/hooks/use-toast';

export function useConfigs() {
  return useQuery({
    queryKey: ['configs'],
    queryFn: () => configsApi.getAll(),
  });
}

export function useUpdateConfig() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: ({ key, value }: { key: string; value: string }) => configsApi.update(key, value),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['configs'] });
      toast({ title: '配置已更新', variant: 'success' as any });
    },
    onError: () => {
      toast({ title: '更新失败', variant: 'destructive' });
    },
  });
}

export function useTransferEnabled() {
  return useQuery({
    queryKey: ['configs', 'transfer-enabled'],
    queryFn: () => configsApi.getTransferEnabled(),
  });
}

export function useSetTransferEnabled() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: (enabled: boolean) => configsApi.setTransferEnabled(enabled),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['configs', 'transfer-enabled'] });
      toast({ title: '划转设置已更新', variant: 'success' as any });
    },
    onError: () => {
      toast({ title: '更新失败', variant: 'destructive' });
    },
  });
}
