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

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

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 = () => {
  return useMutation({
    mutationFn: (id: string) => api.closeTicket(id),
  });
};

export const useCreateCategory = () => {
  return useMutation({
    mutationFn: (variables: CreateCategoryType) =>
      api.createCategory(variables),
  });
};

export const useGetCategories = () => {
  return useQuery({
    queryKey: ["categories"],
    queryFn: () => api.getCategories(),
  });
};

export const useReferTicket = () => {
  return useMutation({
    mutationFn: (variables: { id: string; userId: string }) =>
      api.referTicket(variables.id, variables.userId),
  });
};

export const useOpenTicket = () => {
  return useMutation({
    mutationFn: (id: string) => api.openTicket(id),
  });
};

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

  return useMutation({
    mutationFn: (variables: UpdateCategoryType) =>
      api.updateCategory(id, variables),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["categories"],
      });
    },
  });
};

export const useDeleteCategory = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => api.deleteCategory(id),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["categories"],
      });
    },
  });
};
