import { StoreAction } from 'store/utils/actions';
import produce from 'immer';
import {
  handleRequest,
  handleResponse,
  handleUpdateResponse,
  handleAddResponse,
  handleDeleteResponse,
} from 'store/utils/reducers';
import auth from 'store/auth';
import actions from './actions';

interface OrderState {
  list: {} | null;
  detail: {} | null;
  current: {} | null;
}

export const initialState: OrderState = {
  list: null,
  detail: null,
  current: null,
};

export const treatmentIn = values => {
  const output = { ...values };

  return output;
};

const reducer = (state: OrderState = initialState, action: StoreAction): OrderState => {
  return produce(
    state,
    (draft): OrderState => {
      switch (action.type) {
        case actions.list.request.constant:
          handleRequest(draft, action, 'list', true);
          break;
        case actions.list.result.constant:
          handleResponse(draft, action, 'list', treatmentIn);
          break;
        case actions.update.result.constant:
          handleUpdateResponse(draft, action, 'list', treatmentIn);
          break;
        case actions.detail.result.constant:
          handleResponse(draft, action, 'detail', treatmentIn);
          break;
        case actions.current.request.constant:
          handleRequest(draft, action, 'current');
          break;
        case actions.current.result.constant:
          handleResponse(draft, action, 'current', treatmentIn);
          break;
        case actions.add.result.constant:
          handleResponse(draft, action, 'current', treatmentIn);
          break;
        case actions.finaliseCheckoutWithStripe.result.constant:
          handleResponse(draft, action, 'current', treatmentIn);
          break;
        case actions.delete.result.constant:
          draft.current = null;
          break;
        case auth.actions.logout.result.constant:
          draft.list = null;
          draft.detail = null;
          draft.current = null;
          break;
        default:
      }
    },
  );
};

export default reducer;
