import { createAction, createReducer } from '@reduxjs/toolkit'; import { Order, OrderStatus, TrackingStep, DeliveryAgent, Location } from '../../../interfaces'; // ─── State ─────────────────────────────────────────────────────────────────── export interface OrderState { currentOrder: Order | null; orders: Order[]; trackingSteps: TrackingStep[]; deliveryAgent: DeliveryAgent | null; liveLocation: Location | null; } const initialState: OrderState = { currentOrder: null, orders: [], trackingSteps: [], deliveryAgent: null, liveLocation: null, }; // ─── Helpers ───────────────────────────────────────────────────────────────── const buildTrackingSteps = (status: OrderStatus): TrackingStep[] => { const steps: { key: OrderStatus; label: string }[] = [ { key: 'placed', label: 'Order Placed' }, { key: 'confirmed', label: 'Confirmed' }, { key: 'dispatched', label: 'Dispatched' }, { key: 'delivered', label: 'Delivered' }, ]; const currentIndex = steps.findIndex(s => s.key === status); return steps.map((step, index) => ({ ...step, isCompleted: index < currentIndex, isActive: index === currentIndex, })); }; // ─── Actions ───────────────────────────────────────────────────────────────── export const placeOrder = createAction('order/placeOrder'); export const updateOrderStatus = createAction('order/updateOrderStatus'); export const setDeliveryAgent = createAction('order/setDeliveryAgent'); export const updateLiveLocation = createAction('order/updateLiveLocation'); export const addOrder = createAction('order/addOrder'); // ─── Reducer ───────────────────────────────────────────────────────────────── const orderReducer = createReducer(initialState, builder => { builder .addCase(placeOrder, (state, action) => { state.currentOrder = action.payload; state.orders.unshift(action.payload); state.trackingSteps = buildTrackingSteps('placed'); }) .addCase(updateOrderStatus, (state, action) => { if (state.currentOrder) { state.currentOrder.status = action.payload; state.trackingSteps = buildTrackingSteps(action.payload); const idx = state.orders.findIndex( o => o.id === state.currentOrder!.id, ); if (idx !== -1) { state.orders[idx] = { ...state.orders[idx], status: action.payload, }; } } }) .addCase(setDeliveryAgent, (state, action) => { state.deliveryAgent = action.payload; }) .addCase(updateLiveLocation, (state, action) => { state.liveLocation = action.payload; }) .addCase(addOrder, (state, action) => { state.orders.unshift(action.payload); }); }); export default orderReducer;