import * as api from "../service/CustomerService";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { CreateCustomerType } from "../types/CustomerTypes";

export const useGetCustomers = (page: number, withoutPaginate?: boolean) => {
  return useQuery({
    queryKey: ["customers", page],
    queryFn: () => api.getCustomers(page, withoutPaginate),
  });
};

export const useGetProvines = () => {
  return useQuery({
    queryKey: ["provines"],
    queryFn: () => api.getProvines(),
  });
};

export const useGetCities = (provincesId: string) => {
  return useQuery({
    queryKey: ["cities", provincesId],
    queryFn: () => api.getCities(provincesId),
    enabled: !!provincesId,
  });
};

export const useCreateCustomer = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (variables: CreateCustomerType) =>
      api.createCustomer(variables),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["customers"],
      });
    },
  });
};

export const useGetCustomerDetail = (id?: string) => {
  return useQuery({
    queryKey: ["customer-detail", id],
    queryFn: () => api.getDetailCustomer(id ? id : ""),
    enabled: !!id,
  });
};

export const useUpdateCustomer = (id: string) => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (variables: CreateCustomerType) =>
      api.updateCustomer(id, variables),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["customers"],
      });
    },
  });
};
