import rootReducer from '../reducers';
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { configureStore } from '@reduxjs/toolkit';
import logger from 'redux-logger';
import createSagaMiddleware from 'redux-saga';
import rootSaga from '../sagas'
import { persistStore, persistReducer } from 'redux-persist'
import AsyncStorage from '@react-native-async-storage/async-storage';
import authReducer from '../reducers/auth';
import productReducer from '../reducers/product';
import cartReducer from '../reducers/cart';
import invoiceReducer from '../reducers/invoice';

const sagaMiddleware = createSagaMiddleware()

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  whitelist: ['auth', 'invoice', 'cart', 'product']
}
const authPersistConfig = {
  key: 'auth',
  storage: AsyncStorage,
  whitelist: ['token']
}
const productPersistConfig = {
  key: 'product',
  storage: AsyncStorage,
}
const cartPersistConfig = {
  key: 'cart',
  storage: AsyncStorage,
}
const invoicePersistConfig = {
  key: 'invoice',
  storage: AsyncStorage,
}
export const authPersistedReducer = persistReducer(authPersistConfig, authReducer)
export const productPersistedReducer = persistReducer(productPersistConfig, productReducer)
export const cartPersistedReducer = persistReducer(cartPersistConfig, cartReducer)
export const invoicePersistedReducer = persistReducer(invoicePersistConfig, invoiceReducer)

const persistedReducer = persistReducer(persistConfig, rootReducer)
// const middleware = logger, sagaMiddleware);
const store = createStore(
  persistedReducer,
  applyMiddleware(logger, sagaMiddleware)
)
sagaMiddleware.run(rootSaga)
const persistor = persistStore(store)


export { store, persistor }