import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { inquiryService } from '../services/inquiryService'
import type { InquiryFilters } from '../provider/IInquiryProvider'
import type { Attachment } from '../domain/inquiry'
import { useToastStore } from '../stores/toastStore'

export function useActiveInquiries(filters?: InquiryFilters) {
  return useQuery({
    queryKey: ['inquiries', 'active', filters ?? {}],
    queryFn: () => inquiryService.getActiveInquiries(filters),
    select: (res) => res.data ?? [],
  })
}

export function useInquiryById(id: string) {
  return useQuery({
    queryKey: ['inquiry', id],
    queryFn: () => inquiryService.getInquiryById(id),
    enabled: !!id,
    select: (res) => res.data ?? null,
  })
}

export function useSendInquiryReply() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({
      inquiryId,
      payload,
    }: {
      inquiryId: string
      payload: { subject?: string; body: string; attachments?: Attachment[] }
    }) => inquiryService.sendInquiryReply(inquiryId, payload),
    onSuccess: (_data, { inquiryId }) => {
      qc.invalidateQueries({ queryKey: ['inquiry', inquiryId] })
      qc.invalidateQueries({ queryKey: ['inquiries'] })
    },
    onError: () => {
      useToastStore.getState().showToast('Antwort konnte nicht gesendet werden.', 'error')
    },
  })
}

export function useMarkThreadAsRead() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (id: string) => inquiryService.markThreadAsRead(id),
    onSuccess: (_data, id) => {
      qc.invalidateQueries({ queryKey: ['inquiry', id] })
      qc.invalidateQueries({ queryKey: ['inquiries'] })
    },
  })
}
