import { createReducer, Action, on } from '@ngrx/store';
import { INITIAL_DETAILS_STATE, DetailsState, detailsStateEntityAdapter } from './details.state';
import * as actions from './details.actions';

const _detailsReducer = createReducer(
  INITIAL_DETAILS_STATE,
  on(actions.addOrderItems, (s, a) => {
    if (a.orderItems && a.orderItems.length) {
      const next = detailsStateEntityAdapter.removeMany(
        a.orderItems.map((item) => item.orderItemSubsetId),
        s
      );
      return detailsStateEntityAdapter.addMany(
        a.orderItems.map((items) => ({ ...items, timestamp: Date.now() })),
        next
      );
    }

    return s;
  }),
  on(actions.setComment, (s, a) => {
    const entity = s.entities[a.orderItemSubsetId];
    if (entity) {
      return detailsStateEntityAdapter.updateOne({ id: a.orderItemSubsetId, changes: { specialComment: a.comment } }, s);
    }
    return s;
  }),
  on(actions.cleanup, (s) => detailsStateEntityAdapter.removeAll(s))
);

export function detailsReducer(state: DetailsState, action: Action) {
  return _detailsReducer(state, action);
}
