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 companiesReducer from '../reducers/companiesReducer';
import contractsReducer from '../reducers/contractsReducer';
import contractReducer from '../reducers/contractReducer';
import calendarReducer from '../reducers/calendarReducer';
import eventsReducer from '../reducers/eventsReducer';
import supportReducer from '../reducers/supportReducer';
import adminReducer from '../reducers/adminReducer';
import contractsInfoReducer from '../reducers/contractsInfoReducer';
import contractEventsReducer from '../reducers/contractEventsReducer';

const combinedReducer = combineReducers({ 
	auth: authReducer, 
	user: userReducer, 
	company: companyReducer, 
	companies: companiesReducer, 
	contracts: contractsReducer, 
	contract: contractReducer, 
	calendar: calendarReducer, 
	events: eventsReducer, 
	support: supportReducer, 
	admin: adminReducer, 
	contracts_info: contractsInfoReducer, 
	contract_events: contractEventsReducer, 
});

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: 'lkevoleasing', 
            whitelist: [ 'auth', 'user', 'company', 'companies', 'contracts_info', 'contract_events' ], 
            storage
        };

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

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

        return store;
	}
}

export const reduxWrapper = createWrapper(makeStore);