import { applyMiddleware, combineReducers, compose, createStore } from 'redux'
import thunk from 'redux-thunk'
import { createReduxHistoryContext, reachify } from 'redux-first-history'
import { History } from 'history'
import { ApplicationState, reducers } from './'

export default function configureStore(history: History, initialState?: ApplicationState) {

  const {
    createReduxHistory,
    routerMiddleware,
    routerReducer
  } = createReduxHistoryContext({ history })


  const middleware = [
    thunk,
    routerMiddleware
  ]

  const rootReducer = combineReducers({
    ...reducers,
    router: routerReducer
  })

  const enhancers = []
  const windowIfDefined = typeof window === 'undefined' ? null : window as any // eslint-disable-line @typescript-eslint/no-explicit-any
  if (windowIfDefined && windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__) {
    enhancers.push(windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__())
  }

  const store = createStore(
    rootReducer,
    initialState,
    compose(applyMiddleware(...middleware), ...enhancers))

  const reduxHistory = createReduxHistory(store)

  //if you use @reach/router
  const reachHistory = reachify(reduxHistory)

  return {
    store,
    history: reduxHistory,
    reachHistory
  }
}
