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

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

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

  return useMutation({
    mutationFn: (couponData: CreateCouponType) => api.createCoupon(couponData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["coupons"] });
    },
  });
};

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

  return useMutation({
    mutationFn: (couponId: string) => api.deleteCoupon(couponId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["coupons"] });
    },
  });
};

export const useGetCouponDetail = (couponId: string) => {
  return useQuery({
    queryKey: ["coupon", couponId],
    queryFn: () => api.getCouponDetail(couponId),
  });
};

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