import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuthToken } from "../hooks/use-root-data";
import { useToast } from "../hooks/use-toast";
import { createDiscountManagementApi } from "~/utils/api-client-factory";

// Query keys
export const discountKeys = {
  all: ["discounts"] as const,
  verify: () => [...discountKeys.all, "verify"] as const,
};

// Hook to verify discount code
export function useVerifyDiscountCode() {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  const { toast } = useToast();
  return useMutation({
    mutationFn: async ({ code, cartId }: { code: number; cartId: string }) => {
      try {
        const discountApi = createDiscountManagementApi(token);
        const response = await discountApi.apiDiscountV1DiscountsVerifyCreate({
          data: {
            code,
            cartId,
          },
        });
        return response;
      } catch (error) {
        console.error("Error verifying discount code:", error);
        throw error;
      }
    },
    onSuccess: (response) => {
      if (response.valid) {
        toast({
          title: "تخفیف",
          description: response.message || "تخفیف با موفقیت اعمال شد",
        });
      } else {
        toast({
          title: "خطا",
          description: response.message || "کد تخفیف نامعتبر است",
          variant: "destructive",
        });
      }
      // Invalidate relevant queries (cart details would need to be refreshed)
      queryClient.invalidateQueries({ queryKey: ["carts"] });
      queryClient.invalidateQueries({ queryKey: ["getCouriersService"] });
    },
    onError: (error) => {
      console.error("Error applying discount code:", error);
      toast({
        title: "خطا",
        description: "کد تخفیف نامعتبر است",
        variant: "destructive",
      });
    },
  });
}
