import { createReducer, on, Action } from '@ngrx/store';
import { INITIAL_HISTORY_STATE, historyStateAdapter, HistoryState, INITIAL_ORDER_HISTORY } from './history.state';
import * as actions from './history.actions';
import { OrderHistoryStatus } from '../defs';

export const _historyReducer = createReducer(
  INITIAL_HISTORY_STATE,
  on(actions.initOrderHistory, (s, a) =>
    historyStateAdapter.addOne(
      {
        ...INITIAL_ORDER_HISTORY,
        id: a.id,
      },
      s
    )
  ),
  on(actions.updateOrderHistory, (s, a) =>
    historyStateAdapter.updateOne(
      {
        id: a.id,
        changes: {
          ...a.history,
          status: OrderHistoryStatus.AVAILABLE,
        },
      },
      s
    )
  ),
  on(actions.addOrderHistory, (s, a) =>
    historyStateAdapter.updateOne(
      {
        id: a.id,
        changes: {
          ...s.entities[a.id],
          histories: a.histories,
          status: OrderHistoryStatus.AVAILABLE,
        },
      },
      s
    )
  ),
  on(actions.setStatus, (s, a) =>
    historyStateAdapter.updateOne(
      {
        id: a.id,
        changes: { status: a.status },
      },
      s
    )
  ),
  on(actions.fetchHistory, (s, a) => historyStateAdapter.updateOne({ id: a.id, changes: { status: OrderHistoryStatus.FETCHING } }, s))
);

export function historyReducer(state: HistoryState, action: Action) {
  return _historyReducer(state, action);
}
