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

const initialState = {
  id: null,
  items: [],
  itemCount: 0,
  total: 0,
  loading: false,
  error: null,
};

export const cartSlice = createSlice({
  name: 'cart',
  initialState,
  reducers: {
    cartLoading: (state) => {
      state.loading = true;
      state.error = null;
    },
    cartLoadingFailed: (state, action) => {
      state.loading = false;
      state.error = action.payload;
    },
    updateCart: (state, action) => {
      state.loading = false;
      state.id = action.payload.id;
      state.items = action.payload.items;
      state.itemCount = action.payload.itemCount;
      state.total = action.payload.total;
    },
    clearCart: (state) => {
      state.id = null;
      state.items = [];
      state.itemCount = 0;
      state.total = 0;
    },
    clearCartError: (state) => {
      state.error = null;
    },
  },
});

export const { 
  cartLoading, 
  cartLoadingFailed, 
  updateCart, 
  clearCart, 
  clearCartError 
} = cartSlice.actions;

// Selectors
export const selectCartItems = (state) => state.cart.items;
export const selectCartItemCount = (state) => state.cart.itemCount;
export const selectCartTotal = (state) => state.cart.total;
export const selectCartLoading = (state) => state.cart.loading;
export const selectCartError = (state) => state.cart.error;

export default cartSlice.reducer;