import { configureStore, Middleware } from '@reduxjs/toolkit';
import { persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // defaults to localStorage for web
import { combineReducers } from '@reduxjs/toolkit';

// Slices
import authReducer from './slices/authSlice';
import offlineReducer from './slices/offlineSlice';
import activitiesReducer from './slices/activitiesSlice';
import childrenReducer from './slices/childrenSlice';
import networkReducer from './slices/networkSlice';

// Middleware
import { offlineMiddleware } from './middleware/offlineMiddleware';
import { syncMiddleware } from './middleware/syncMiddleware';

// Persist configuration
const persistConfig = {
  key: 'root',
  version: 1,
  storage,
  // Only persist these slices (exclude network status as it should be fresh on reload)
  whitelist: ['auth', 'offline', 'activities', 'children'],
};

const rootReducer = combineReducers({
  auth: authReducer,
  offline: offlineReducer,
  activities: activitiesReducer,
  children: childrenReducer,
  network: networkReducer,
});

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        // Ignore redux-persist action types
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER, 'persist/PERSIST', 'persist/REHYDRATE'],
        // Ignore these field paths in all actions
        ignoredActionPaths: ['meta.arg', 'payload.timestamp', 'register'],
        // Ignore these paths in the state
        ignoredPaths: ['items.dates', 'register'],
      },
    }).concat(offlineMiddleware, syncMiddleware),
});

export const persistor = persistStore(store);

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

// Export store instance
export default store;
