import { useMutation, useQueryClient } from '@tanstack/react-query'
import { annotationsApi } from '../api/endpoints'
import type { CreateAnnotationRequest, AnnotationOverrideRequest } from '../api/types'

export const useAnnotations = (documentId: string) => {
  const queryClient = useQueryClient()

  const createMutation = useMutation({
    mutationFn: (annotation: CreateAnnotationRequest) =>
      annotationsApi.create(documentId, annotation),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['document', documentId] })
    },
  })

  const updateMutation = useMutation({
    mutationFn: ({
      annotationId,
      updates,
    }: {
      annotationId: string
      updates: Partial<CreateAnnotationRequest>
    }) => annotationsApi.update(documentId, annotationId, updates),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['document', documentId] })
    },
  })

  const deleteMutation = useMutation({
    mutationFn: (annotationId: string) =>
      annotationsApi.delete(documentId, annotationId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['document', documentId] })
    },
  })

  const verifyMutation = useMutation({
    mutationFn: (annotationId: string) =>
      annotationsApi.verify(documentId, annotationId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['document', documentId] })
    },
  })

  const overrideMutation = useMutation({
    mutationFn: ({
      annotationId,
      overrideData,
    }: {
      annotationId: string
      overrideData: AnnotationOverrideRequest
    }) => annotationsApi.override(documentId, annotationId, overrideData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['document', documentId] })
    },
  })

  return {
    createAnnotation: createMutation.mutate,
    isCreating: createMutation.isPending,
    updateAnnotation: updateMutation.mutate,
    isUpdating: updateMutation.isPending,
    deleteAnnotation: deleteMutation.mutate,
    isDeleting: deleteMutation.isPending,
    verifyAnnotation: verifyMutation.mutate,
    isVerifying: verifyMutation.isPending,
    overrideAnnotation: overrideMutation.mutate,
    isOverriding: overrideMutation.isPending,
  }
}
