import { createStore, Store, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import {
  ConsoleReporter,
  MultiReporter,
  SpadeReporter,
} from 'tachyon-spade-reporter';

import { trackerMiddleware } from 'mweb/common/tracking/middleware';
import { buildRootReducer, RootState } from 'mweb/common/reducers/root';

export default function configureStore(
  initialState?: RootState,
): Store<RootState> {
  const loggers = [new ConsoleReporter()];

  if (initialState && initialState.tracking && initialState.tracking.spadeURI) {
    loggers.push(new SpadeReporter(initialState.tracking.spadeURI));
  }
  const logger = new MultiReporter(loggers);

  let middleware = applyMiddleware(thunk, trackerMiddleware(logger));
  let composeEnhancer = compose;

  if (
    typeof window !== 'undefined' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
  ) {
    composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
  }

  const store = createStore<RootState>(
    buildRootReducer(),
    initialState as any, // hack to beat the bad typing of createStore
    composeEnhancer(middleware),
  );

  if ((module as any).hot) {
    (module as any).hot.accept('mweb/common/reducers/root', () => {
      store.replaceReducer(buildRootReducer());
    });
  }

  return store;
}
