import { NgModule } from '@angular/core';
import { EffectsModule } from '@ngrx/effects';
import { ActionReducer, MetaReducer, StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment';
import { rootReducer } from './store/root.reducer';
import { RootState } from './store/root.state';

export function storeInLocalStorage(
  reducer: ActionReducer<any>,
): ActionReducer<any> {
  return function (state, action) {
    if (action.type === 'HYDRATE') {
      return reducer(action['payload'], action);
    }
    return reducer(state, action);
  };
}

export const metaReducers: MetaReducer<RootState>[] = !environment.production
  ? [storeInLocalStorage]
  : [storeInLocalStorage];

@NgModule({
  imports: [
    StoreModule.forRoot(rootReducer, { metaReducers }),
    EffectsModule.forRoot([]),
    StoreDevtoolsModule.instrument({
      name: 'ISA Ngrx Application Store',
      connectInZone: true,
    }),
  ],
})
export class AppStoreModule {}
