/**
 * 用户待办操作 Hooks
 * 使用 React Query 进行数据获取和缓存管理
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { pendingActionService } from '@/services/pendingActionService';
import type {
  QueryPendingActionsParams,
  CreatePendingActionRequest,
  BatchCreatePendingActionRequest,
  UpdatePendingActionRequest,
} from '@/types/pending-action.types';

/** Query Keys */
export const pendingActionKeys = {
  all: ['pendingActions'] as const,
  list: (params: QueryPendingActionsParams) => [...pendingActionKeys.all, 'list', params] as const,
  detail: (id: string) => [...pendingActionKeys.all, 'detail', id] as const,
};

/**
 * 获取待办操作列表
 */
export function usePendingActions(params: QueryPendingActionsParams = {}) {
  return useQuery({
    queryKey: pendingActionKeys.list(params),
    queryFn: () => pendingActionService.getList(params),
    staleTime: 30 * 1000, // 30秒后标记为过期
    gcTime: 5 * 60 * 1000, // 5分钟后垃圾回收
  });
}

/**
 * 获取单个待办操作详情
 */
export function usePendingActionDetail(id: string) {
  return useQuery({
    queryKey: pendingActionKeys.detail(id),
    queryFn: () => pendingActionService.getDetail(id),
    enabled: !!id,
    staleTime: 60 * 1000,
    gcTime: 5 * 60 * 1000,
  });
}

/**
 * 创建待办操作
 */
export function useCreatePendingAction() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: CreatePendingActionRequest) => pendingActionService.create(data),
    onSuccess: () => {
      // 创建成功后刷新列表
      queryClient.invalidateQueries({ queryKey: pendingActionKeys.all });
    },
  });
}

/**
 * 批量创建待办操作
 */
export function useBatchCreatePendingActions() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: BatchCreatePendingActionRequest) => pendingActionService.batchCreate(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: pendingActionKeys.all });
    },
  });
}

/**
 * 更新待办操作
 */
export function useUpdatePendingAction() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdatePendingActionRequest }) =>
      pendingActionService.update(id, data),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: pendingActionKeys.all });
      queryClient.invalidateQueries({ queryKey: pendingActionKeys.detail(id) });
    },
  });
}

/**
 * 取消待办操作
 */
export function useCancelPendingAction() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => pendingActionService.cancel(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: pendingActionKeys.all });
    },
  });
}

/**
 * 删除待办操作
 */
export function useDeletePendingAction() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => pendingActionService.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: pendingActionKeys.all });
    },
  });
}
