import makeClient from "@/lib/ApolloClientBrowser";
import { PayloadAction, createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import {CartDetail} from "@/types/cart/type";
import { GET_CART_ITEM } from "@/graphql";

import { formatCartDetail } from "@/utils/cartDetailTools";
export interface CartState {
  cart: CartDetail | null;
  loading: boolean;
  error: string | null;
}

// 定义异步 action
export const fetchCartDetail = createAsyncThunk(
  'cartDetail/fetchCartDetail',
  async (_, { rejectWithValue }) => { //_ 占位，表示不需要参数
    try {
      const apolloClient = makeClient();
      const res = await apolloClient.mutate({
        mutation: GET_CART_ITEM,
        fetchPolicy: 'network-only', // 按需调整
      });
      const responseData = res.data?.createReadCart?.readCart;
      return responseData ? formatCartDetail(responseData) : null;
    } catch (error) {
      let errorMessage: string;
      if (error instanceof Error) {
        errorMessage = error.message;
      } else {
        errorMessage = String(error);
      }
      return rejectWithValue(errorMessage);
    }
  }
);


const initialState: CartState = {
  cart: null,
  loading: false,
  error: null,
};

const cartSlice = createSlice({
  name: "cartDetail",
  initialState,
  reducers: {
    addItem: (state, action: PayloadAction<CartDetail>) => {
      state.cart = { ...action.payload };
    },
    updateCart: (state, action: PayloadAction<Partial<CartDetail>>) => {
      if (state.cart) {
        state.cart = { ...state.cart, ...action.payload };
      }
    },
    clearCart(state) {
      state.cart = null;
      state.loading = false;
      state.error = null;
    },

  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchCartDetail.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchCartDetail.fulfilled, (state, action) => {
        state.loading = false;
        state.cart = action.payload;
      })
      .addCase(fetchCartDetail.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const {
  addItem,
  updateCart,
  clearCart,
} = cartSlice.actions;

export default cartSlice.reducer;
