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

export interface UseTenantsOptions {
  page?: number;
  pageSize?: number;
  keyword?: string;
  filters?: Record<string, unknown>;
}

export function useTenants(options: UseTenantsOptions = {}) {
  const {
    page = 1,
    pageSize = 10,
    keyword = '',
    filters = {}
  } = options;

  const queryClient = useQueryClient();

  const query = useQuery({
    queryKey: ['tenants', page, pageSize, keyword, filters],
    queryFn: async () => {
      const res = await tenantClientManager.get().index.$get({
        query: {
          page,
          pageSize,
          keyword,
          filters: Object.keys(filters).length > 0 ? JSON.stringify(filters) : undefined
        }
      });

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

      return await res.json();
    }
  });

  const createMutation = useMutation({
    mutationFn: async (data: Parameters<typeof tenantClient.index.$post>[0]['json']) => {
      const res = await tenantClientManager.get().index.$post({ json: data });
      if (res.status !== 201) {
        throw new Error('创建租户失败');
      }
      return await res.json();
    },
    onSuccess: () => {
      toast.success('租户创建成功');
      queryClient.invalidateQueries({ queryKey: ['tenants'] });
    },
    onError: () => {
      toast.error('创建失败，请重试');
    }
  });

  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: Parameters<typeof tenantClient[':id']['$put']>[0]['json'] }) => {
      const res = await tenantClientManager.get()[':id']['$put']({
        param: { id },
        json: data
      });
      if (res.status !== 200) {
        throw new Error('更新租户失败');
      }
      return await res.json();
    },
    onSuccess: () => {
      toast.success('租户更新成功');
      queryClient.invalidateQueries({ queryKey: ['tenants'] });
    },
    onError: () => {
      toast.error('更新失败，请重试');
    }
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await tenantClientManager.get()[':id']['$delete']({
        param: { id }
      });
      if (res.status !== 204) {
        throw new Error('删除租户失败');
      }
    },
    onSuccess: () => {
      toast.success('租户删除成功');
      queryClient.invalidateQueries({ queryKey: ['tenants'] });
    },
    onError: () => {
      toast.error('删除失败，请重试');
    }
  });

  return {
    ...query,
    createTenant: createMutation.mutateAsync,
    updateTenant: updateMutation.mutateAsync,
    deleteTenant: deleteMutation.mutateAsync,
    isCreating: createMutation.isPending,
    isUpdating: updateMutation.isPending,
    isDeleting: deleteMutation.isPending
  };
}