import { createStore, combineReducers } from 'redux';
import { createWrapper } from 'next-redux-wrapper';

import authReducer from '../reducers/authReducer';
import userReducer from '../reducers/userReducer';
import companyReducer from '../reducers/companyReducer';
import contractsReducer from '../reducers/contractsReducer';
import contractReducer from '../reducers/contractReducer';
import calendarReducer from '../reducers/calendarReducer';

const combinedReducer = combineReducers({ 
	auth: authReducer, 
	user: userReducer, 
	company: companyReducer, 
	contracts: contractsReducer, 
	contract: contractReducer, 
	calendar: calendarReducer, 
});

const makeStore = (context) => 
{
	const isServer = typeof window === 'undefined';

    if(isServer) 
	{
		return createStore(combinedReducer);
    } 
	else 
	{
		const { persistStore, persistReducer } = require('redux-persist');
        const storage = require('redux-persist/lib/storage').default;

        const persistConfig = {
            key: 'nextjs', 
            whitelist: [ 'auth', 'user', 'company', ], 
            storage
        };

        const persistedReducer = persistReducer(persistConfig, combinedReducer);
        const store = createStore(persistedReducer);

        store.__persistor = persistStore(store);
		window.store = store;

        return store;
	}
}

export const reduxWrapper = createWrapper(makeStore);