"use client";

import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchCartDetail } from "@/store/slices/cart-slice";
import { useCallback, useEffect } from "react";
import { getCartToken } from "@/utils/getCartToken";


export function useCartDetail() {
  const dispatch = useAppDispatch();
  const cartDetail = useAppSelector((state) => state.cartDetail);
  const {cart, loading, error} = cartDetail;

  const getCartDetail = useCallback(async () => {
    const token = getCartToken();
    if (!token) {
      return;
    }
    dispatch(fetchCartDetail()); 
  }, [dispatch]);

  // useCartDetail在组件中被调用时就会触发useEffect
  // 初始化执行一次，获取购物车数据
  useEffect(() => {
    if (cart === null && !loading) {
      getCartDetail();
    }
  }, [getCartDetail]);  

  return {
    cartData: cart,
    getCartDetail,
    isLoading: loading,
    error,
  };
}
