"use client"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { createSupportTicket, createSupportTicketQueryKey, getSupportTickets, getSupportTicketsQueryKey } from "../queries/support"
import { useToaster } from "@/context/ToasterContext"
import type { CreateSupportTicketPayload } from "@/types/support"

export function useCreateSupportTicket() {
  const toast = useToaster()
  const queryClient = useQueryClient()
  return useMutation({
    mutationKey: createSupportTicketQueryKey,
    mutationFn: (payload: CreateSupportTicketPayload) => createSupportTicket(payload),
    onSuccess: (data) => {
      toast.showSuccess("Support ticket submitted successfully. We'll get back to you soon!")
      // Invalidate the tickets query to refetch the list
      queryClient.invalidateQueries({ queryKey: getSupportTicketsQueryKey(data.requesterId) })
    },
    onError: error => {
      console.error("Support ticket creation failed:", error)
      toast.showError("Failed to submit support ticket. Please try again.")
    }
  })
}

export function useGetSupportTickets(requesterId: string) {
  return useQuery({
    queryKey: getSupportTicketsQueryKey(requesterId),
    queryFn: () => getSupportTickets(requesterId),
    enabled: !!requesterId
  })
}