import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { QUERY_KEYS } from "@/utils/query-key";
import toast from "react-hot-toast";
import {
  getDiscountCodes,
  getDiscountCode,
  createDiscountCode,
  updateDiscountCode,
  deleteDiscountCode,
  getDiscountReports,
} from "./_requests";
import {
  CreateDiscountCodeRequest,
  UpdateDiscountCodeRequest,
  DiscountCodeFilters,
  DiscountReportFilters,
} from "./_models";

export const useDiscountCodes = (filters?: DiscountCodeFilters) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_DISCOUNT_CODES, filters],
    queryFn: () => getDiscountCodes(filters),
  });
};

export const useDiscountCode = (id: string) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_DISCOUNT_CODE, id],
    queryFn: () => getDiscountCode(id),
    enabled: !!id,
  });
};

export const useCreateDiscountCode = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (payload: CreateDiscountCodeRequest) =>
      createDiscountCode(payload),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_DISCOUNT_CODES],
      });
      toast.success("کد تخفیف با موفقیت ایجاد شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در ایجاد کد تخفیف");
    },
  });
};

export const useUpdateDiscountCode = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (payload: UpdateDiscountCodeRequest) =>
      updateDiscountCode(payload.id.toString(), payload),
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_DISCOUNT_CODES],
      });
      if (data?.id) {
        queryClient.invalidateQueries({
          queryKey: [QUERY_KEYS.GET_DISCOUNT_CODE, data.id.toString()],
        });
      }
      toast.success("کد تخفیف با موفقیت به‌روزرسانی شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در به‌روزرسانی کد تخفیف");
    },
  });
};

export const useDeleteDiscountCode = () => {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => deleteDiscountCode(id),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_DISCOUNT_CODES],
      });
      toast.success("کد تخفیف با موفقیت حذف شد");
    },
    onError: (error: any) => {
      toast.error(error?.message || "خطا در حذف کد تخفیف");
    },
  });
};

export const useDiscountReports = (
  filters?: DiscountReportFilters,
  enabled: boolean = true
) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_DISCOUNT_REPORTS, filters],
    queryFn: () => getDiscountReports(filters),
    enabled,
  });
};
