import * as api from "../service/CouponService";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import type { CreateCouponType } from "../types/Types";

export const useGetCoupons = () => {
  return useQuery({
    queryKey: ["coupons"],
    queryFn: api.getCoupons,
  });
};

export const useDeleteCoupon = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.deleteCoupon,
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["coupons"],
      });
    },
  });
};

export const useCreateCoupon = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: api.createCoupon,
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: ["coupons"],
      });
    },
  });
};

export const useGenerateCouponCode = () => {
  return useMutation({
    mutationFn: api.generateCouponCode,
  });
};

export const useGetCouponDetails = (id: string) => {
  return useQuery({
    queryKey: ["coupon", id],
    queryFn: () => api.getCouponDetails(id),
    enabled: !!id,
  });
};

export const useUpdateCoupon = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, params }: { id: string; params: CreateCouponType }) =>
      api.updateCoupon(id, params),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({
        queryKey: ["coupons"],
      });
      queryClient.invalidateQueries({
        queryKey: ["coupon", id],
      });
    },
  });
};
