import * as api from "../service/TicketService";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AddMessageTicketType, CreateTicketType } from "../types/TicketTypes";

export const useGetTickets = (status: string) => {
  return useQuery({
    queryKey: ["tickets", status],
    queryFn: () => api.getTickets(status),
  });
};

export const useCreateTicket = () => {
  return useMutation({
    mutationFn: (variables: CreateTicketType) => api.createTicket(variables),
  });
};

export const useGetCategoriesTicket = () => {
  return useQuery({
    queryKey: ["category-tickets"],
    queryFn: () => api.getCategoriesTicket(),
  });
};

export const useSingleUpload = (callback?: (value: number) => void) => {
  return useMutation({
    mutationFn: (variables: FormData) => api.uploadSingle(variables, callback),
  });
};
export const useMultiUpload = (callback?: (value: number) => void) => {
  return useMutation({
    mutationFn: (variables: FormData) =>
      api.uploadMultiple(variables, callback),
  });
};

export const useGetMessages = (id: string) => {
  return useQuery({
    queryKey: ["ticket-messages", id],
    queryFn: () => api.getMessages(id),
    enabled: !!id,
  });
};

export const useAddMessageTicket = (id: string) => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (variables: AddMessageTicketType) =>
      api.addMessageTicket(id, variables),
    onSuccess: () => {
      queryClient.refetchQueries({
        queryKey: ["ticket-messages", id],
      });
    },
  });
};

export const useCloseTicket = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => api.closeTicket(id),
    onSuccess: () => {
      queryClient.refetchQueries({
        queryKey: ["tickets"],
      });
      queryClient.refetchQueries({
        queryKey: ["ticket-messages"],
      });
    },
  });
};
