import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface CartItem {
  skuId: string; // ProductSKU id
  productId: string; // base Product id
  quantity: number;
  price?: number; // price at time of adding
}

interface CartState {
  items: CartItem[];
}

const initialState: CartState = {
  items: [],
};

const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {
    setCart(state, action: PayloadAction<CartItem[]>) {
      state.items = action.payload;
    },

    addItemToCart(state, action: PayloadAction<CartItem>) {
      const item = action.payload;
      const idx = state.items.findIndex(i => i.skuId === item.skuId);
      if (idx > -1) {
        state.items[idx].quantity += item.quantity;
      } else {
        state.items.push(item);
      }
    },

    removeItem(state, action: PayloadAction<{ skuId: string }>) {
      state.items = state.items.filter(i => i.skuId !== action.payload.skuId);
    },

    updateQuantity(state, action: PayloadAction<{ skuId: string; quantity: number }>) {
      const idx = state.items.findIndex(i => i.skuId === action.payload.skuId);
      if (idx > -1) state.items[idx].quantity = action.payload.quantity;
    },

    clearCart(state) {
      state.items = [];
    },
  },
});

export const { setCart, addItemToCart, removeItem, updateQuantity, clearCart } = cartSlice.actions;
export default cartSlice.reducer;
