import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { tenantClient } from '@/api/tenantClient';
import { toast } from 'sonner';

export function useTenantConfig(tenantId: number) {
  const queryClient = useQueryClient();

  const query = useQuery({
    queryKey: ['tenant-config', tenantId],
    queryFn: async () => {
      const res = await tenantClient[':id'].$get({
        param: { id: tenantId }
      });

      if (res.status !== 200) {
        throw new Error('获取租户配置失败');
      }

      const tenant = await res.json();
      return tenant.config || {};
    },
    enabled: !!tenantId
  });

  const updateMutation = useMutation({
    mutationFn: async (config: Record<string, unknown>) => {
      const res = await tenantClient[':id']['$put']({
        param: { id: tenantId },
        json: { config }
      });
      if (res.status !== 200) {
        throw new Error('更新租户配置失败');
      }
      return await res.json();
    },
    onSuccess: () => {
      toast.success('租户配置更新成功');
      queryClient.invalidateQueries({ queryKey: ['tenant-config', tenantId] });
      queryClient.invalidateQueries({ queryKey: ['tenants'] });
    },
    onError: () => {
      toast.error('更新配置失败，请重试');
    }
  });

  return {
    ...query,
    updateConfig: updateMutation.mutateAsync,
    isUpdating: updateMutation.isPending
  };
}