import { createStore, combineReducers, compose, applyMiddleware } from 'redux'
import reducers from '../reducers'
import { reducer as formReducer } from 'redux-form'
import { routerReducer, routerMiddleware } from 'react-router-redux'
import createSagaMiddleware from 'redux-saga'
import rootSaga from '../sagas'
import { getHistory } from '../history'
import { getToken } from '../utils/callApi'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

export const configureStore = (initialState = {
  auth: {
    token: getToken() ? getToken() : null
  }
}) => {
  const saga = createSagaMiddleware()
  const router = routerMiddleware(getHistory())
  const reducer = combineReducers({
    form: formReducer,
    router: routerReducer,
    ...reducers,
  });
  const enhancer = composeEnhancers(
    applyMiddleware(saga, router)
  )
  const store = createStore(reducer, initialState, enhancer)

  saga.run(rootSaga, store).done.catch((e) => {
    store.dispatch({
      type: 'lol',
    })
  })


  return {
    ...store,
    getReducer() {
      return reducer
    }
  }
}

