import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  getDisclosureRequests, getMyDisclosureRequests,
  reviewDisclosure, revokeDisclosure, adminRevokeDisclosure,
  deleteDisclosure, requestDisclosure,
  adminDeleteDisclosure, adminReactivateDisclosure,
} from '@/services/disclosureService'

export function useDisclosures(status?: string) {
  return useQuery({
    queryKey: ['disclosures', status ?? 'all'],
    queryFn: () => getDisclosureRequests(status),
  })
}

export function useMyDisclosures() {
  return useQuery({
    queryKey: ['my-disclosures'],
    queryFn: getMyDisclosureRequests,
  })
}

export function useReviewDisclosure() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ id, status }: { id: number; status: 'approved' | 'rejected' }) =>
      reviewDisclosure(id, status),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['disclosures'] })
      queryClient.invalidateQueries({ queryKey: ['notifications'] })
    },
  })
}

export function useRevokeDisclosure() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: number) => revokeDisclosure(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['my-disclosures'] })
      queryClient.invalidateQueries({ queryKey: ['cases'] })
    },
  })
}

export function useAdminRevokeDisclosure() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: number) => adminRevokeDisclosure(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['disclosures'] })
      queryClient.invalidateQueries({ queryKey: ['notifications'] })
    },
  })
}

export function useDeleteDisclosure() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: number) => deleteDisclosure(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['my-disclosures'] })
    },
  })
}

export function useRequestDisclosure() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: ({ caseId, reason }: { caseId: number; reason: string }) =>
      requestDisclosure(caseId, reason),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['my-disclosures'] })
      queryClient.invalidateQueries({ queryKey: ['notifications'] })
    },
  })
}

export function useAdminDeleteDisclosure() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: number) => adminDeleteDisclosure(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['disclosures'] })
    },
  })
}

export function useAdminReactivateDisclosure() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (id: number) => adminReactivateDisclosure(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['disclosures'] })
      queryClient.invalidateQueries({ queryKey: ['notifications'] })
    },
  })
}
