import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query/react";
import { createInjectorsEnhancer } from "redux-injectors";
import createSagaMiddleware from "redux-saga";
import { createReducer } from "./reducers.js";
import { enableHotReloading } from "./webpack-hmr.js";
import { queryMiddleware } from "./queryMiddleware.js";
import { listenerMiddleware } from "./listenerMiddleware.js";
let rootReducer = createReducer();
let appStore = null;
const setStore = (store) => {
  appStore = store;
};
const getStore = () => appStore;
const createStore = (initialState, sagaMiddleware, history, middlewareConfig = {}, injectedReducers = {}) => {
  const { run: runSaga } = sagaMiddleware;
  const enhancers = [
    createInjectorsEnhancer({
      createReducer,
      runSaga
    })
  ];
  rootReducer = createReducer(injectedReducers);
  const baseStore = configureStore({
    reducer: rootReducer,
    middleware: (getDefaultMiddleware) => getDefaultMiddleware(middlewareConfig).prepend(listenerMiddleware.middleware).concat([sagaMiddleware, queryMiddleware]),
    devTools: true,
    preloadedState: initialState,
    enhancers
  });
  setupListeners(baseStore.dispatch);
  enableHotReloading(baseStore);
  return baseStore;
};
const createAppStore = (initialState = {}, history, middlewareConfig, injectedReducers) => {
  const sagaMiddleware = createSagaMiddleware({});
  const store = createStore(
    initialState,
    sagaMiddleware,
    history,
    middlewareConfig,
    injectedReducers
  );
  setStore(store);
  return store;
};
export {
  createAppStore,
  getStore,
  setStore
};
