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

const initialState = {
  id: null,
  items: [],
  itemCount: 0,
  total: 0,
  subtotal: 0,
  couponCode: null,
  couponDiscount: 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;
      state.subtotal = action.payload.subtotal || action.payload.total;
      state.couponCode = action.payload.couponCode || null;
      state.couponDiscount = action.payload.couponDiscount || 0;
    },
    clearCart: (state) => {
      state.id = null;
      state.items = [];
      state.itemCount = 0;
      state.total = 0;
      state.subtotal = 0;
      state.couponCode = null;
      state.couponDiscount = 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 selectCartSubtotal = (state) => state.cart.subtotal;
export const selectCouponCode = (state) => state.cart.couponCode;
export const selectCouponDiscount = (state) => state.cart.couponDiscount;
export const selectCartLoading = (state) => state.cart.loading;
export const selectCartError = (state) => state.cart.error;

export default cartSlice.reducer;