import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { DocumentService, type AIAnalysisResult } from '@/services/document.service';
import type { CreateDocumentRequest, UpdateDocumentRequest } from '@/types';

export function useDocuments(params?: { page?: number; limit?: number }) {
  return useQuery({
    queryKey: ['documents', params],
    queryFn: () => DocumentService.getUserDocuments(params),
  });
}

export function useDocument(id: string) {
  return useQuery({
    queryKey: ['document', id],
    queryFn: () => DocumentService.getById(id),
    enabled: !!id,
  });
}

export function useCreateDocument() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: CreateDocumentRequest) => DocumentService.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] });
    },
  });
}

export function useUpdateDocument() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateDocumentRequest }) =>
      DocumentService.update(id, data),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['documents'] });
      queryClient.invalidateQueries({ queryKey: ['document', variables.id] });
    },
  });
}

export function useDeleteDocument() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => DocumentService.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] });
    },
  });
}

export function useSearchDocuments() {
  return useMutation({
    mutationFn: (query: string) => DocumentService.search(query),
  });
}

// AI 分析相关 hooks
export function useDocumentAnalysis(id: string) {
  return useQuery({
    queryKey: ['document-analysis', id],
    queryFn: () => DocumentService.getAnalysis(id),
    enabled: !!id,
  });
}

export function useAnalyzeDocument() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, options }: { id: string; options?: { provider?: string; generate_summary?: boolean } }) =>
      DocumentService.analyzeDocument(id, options),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['document-analysis', variables.id] });
    },
  });
}

export function useDeleteDocumentAnalysis() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => DocumentService.deleteAnalysis(id),
    onSuccess: (_, id) => {
      queryClient.invalidateQueries({ queryKey: ['document-analysis', id] });
    },
  });
}
