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

const initialState = {}

const cartSlice = createSlice({
    name: 'cart',
    initialState,
    reducers: {
        CartAdd(state, action) {
            const {good, count=1} = action.payload
            if (good._id in state) {
                state[good._id].count += count
            } else {
            state[good._id] = {good, count}
            }
        },
        CartIncOne(state, action) {
            const { good, count = 1 } = action.payload
            if (good._id in state) {
                if ((state[good._id].count - count) <= 0) {
                    delete state[good._id]
                } else {
                    state[good._id].count -= count
                }
            }
        },
        CartDel(state, action) {
            const { good, count = 1 } = action.payload
            if (good._id in state) {
                delete state[good._id]
            }
          },
        
         CartSet(state, action) {
            const { good, count = 1 } = action.payload
            if (good._id in state && count <= 0) {
                delete state[good._id]
            } else {
                state[good._id].count = count
            }
        },
        CartClear() { 
            return initialState
        }
    }

})

export const {CartAdd, CartIncOne, CartDel, CartSet, CartClear} = cartSlice.actions

export default cartSlice.reducer