import {createSlice, PayloadAction} from "@reduxjs/toolkit";
import {noShippingWarehouse, ShippingWarehouse} from "../../types/shippingWarehouse";

export interface ShippingWarehouseSelectState {
    shippingWarehouses: ShippingWarehouse[]
    selectedShippingWarehouse: ShippingWarehouse
    initialized: boolean
}

const initialState: ShippingWarehouseSelectState = {
    shippingWarehouses: [],
    selectedShippingWarehouse: noShippingWarehouse,
    initialized: false
}

export const shippingWarehouseSelect = createSlice({
    name: 'shippingWarehouse',
    initialState,
    reducers: {
        initializeShippingWarehouseSelect: (state, action: PayloadAction<ShippingWarehouse[]>) => {
            state.shippingWarehouses = action.payload;
            state.initialized = true;
            if (state.shippingWarehouses.length > 0) state.selectedShippingWarehouse = state.shippingWarehouses[0];
        },
        selectShippingWarehouse: (state, action: PayloadAction<{ shippingWarehouseId: number }>) => {
            let selectedWarehouse = state.shippingWarehouses.find(wh => wh.id == action.payload.shippingWarehouseId);
            if (!selectedWarehouse) return;
            state.selectedShippingWarehouse = selectedWarehouse;
        }

    }
})

export const {initializeShippingWarehouseSelect, selectShippingWarehouse} = shippingWarehouseSelect.actions;
export default shippingWarehouseSelect.reducer;