/*
 * File: index.ts
 * Description: Main Redux store configuration with Redux Persist
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */

import { configureStore, combineReducers } from '@reduxjs/toolkit';
import { persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from 'redux-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';

// Import all slice reducers from their respective modules
import authReducer from '../modules/Auth/redux/authSlice';
import dashboardReducer from '../modules/Dashboard/redux/dashboardSlice';
import aiDashboardReducer from '../modules/Dashboard/redux/aiDashboardSlice';
import patientCareReducer from '../modules/PatientCare/redux/patientCareSlice';
import alertsReducer from '../modules/Dashboard/redux/alertsSlice';
import settingsReducer from '../modules/Settings/redux/settingsSlice';
import uiReducer from '../modules/Dashboard/redux/uiSlice';
import hospitalReducer from '../modules/Auth/redux/hospitalSlice';
import aiPredictionReducer from '../modules/AIPrediction/redux/aiPredictionSlice';

// ============================================================================
// REDUX PERSIST CONFIGURATION
// ============================================================================

/**
 * Redux Persist Configuration
 * 
 * Purpose: Configure how Redux state is persisted to AsyncStorage
 * 
 * Features:
 * - AsyncStorage as storage engine
 * - Selective persistence (not all state needs to be persisted)
 * - Migration support for app updates
 * - Debug mode for development
 */
const persistConfig = {
  // Storage engine (AsyncStorage for React Native)
  storage: AsyncStorage,
  
  // Key for the persisted state in AsyncStorage
  key: 'neoscan_physician_store',
  
  // Version for migration support
  version: 1,
  
  // Whitelist: Only persist these reducers
  whitelist: [
    'auth',        // Authentication state (user login, tokens)
    'settings',    // User preferences and settings
    'patientCare', // Patient data cache
    'aiPrediction', // AI prediction data cache
  ],
  
  // Blacklist: Don't persist these reducers
  blacklist: [
    'ui',          // UI state (loading, modals, etc.)
    'alerts',      // Temporary alerts and notifications
    'dashboard',   // Real-time dashboard data
    'aiDashboard', // AI dashboard statistics (fetched fresh each time)
    'hospital',    // Hospital data (fetched fresh each time)
  ],
  
  // Migration configuration for app updates
  migrate: (state: any) => {
    // Handle state migrations when app version changes
    return Promise.resolve(state);
  },
  
  // Serialization options
  serialize: true,
  
  // Timeout for storage operations
  timeout: 10000,
};

// ============================================================================
// ROOT REDUCER
// ============================================================================

/**
 * Root Reducer
 * 
 * Purpose: Combine all slice reducers into a single root reducer
 * 
 * Structure:
 * - auth: Authentication and user management
 * - dashboard: ER dashboard data and statistics
 * - aiDashboard: AI analysis dashboard statistics
 * - patientCare: Patient information and medical records
 * - aiPrediction: AI prediction cases and analysis
 * - alerts: Critical alerts and notifications
 * - settings: User preferences and app settings
 * - ui: User interface state (loading, modals, etc.)
 */
const rootReducer = combineReducers({
  auth: authReducer,
  dashboard: dashboardReducer,
  aiDashboard: aiDashboardReducer,
  patientCare: patientCareReducer,
  aiPrediction: aiPredictionReducer,
  alerts: alertsReducer,
  settings: settingsReducer,
  ui: uiReducer,
  hospital: hospitalReducer,
});

// ============================================================================
// PERSISTED REDUCER
// ============================================================================

/**
 * Persisted Reducer
 * 
 * Purpose: Wrap the root reducer with Redux Persist functionality
 * 
 * Features:
 * - Automatic state persistence to AsyncStorage
 * - State rehydration on app startup
 * - Selective persistence based on whitelist/blacklist
 */
const persistedReducer = persistReducer(persistConfig, rootReducer);

// ============================================================================
// STORE CONFIGURATION
// ============================================================================

/**
 * Redux Store Configuration
 * 
 * Purpose: Configure the Redux store with middleware and persistence
 * 
 * Features:
 * - Redux Toolkit for simplified Redux setup
 * - Redux Persist for state persistence
 * - Development tools integration
 * - Error handling and logging
 */
export const store = configureStore({
  // Use the persisted reducer
  reducer: persistedReducer,
  
  // Middleware configuration
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      // Configure serializable check for Redux Persist actions
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
      
    }),
  
  // Preloaded state (for SSR or initial state)
  preloadedState: undefined,
});

// ============================================================================
// PERSISTOR CONFIGURATION
// ============================================================================

/**
 * Redux Persistor
 * 
 * Purpose: Handle state persistence and rehydration
 * 
 * Features:
 * - Automatic state saving to AsyncStorage
 * - State restoration on app startup
 * - Migration handling for app updates
 * - Error handling for storage operations
 */
export const persistor = persistStore(store);

// ============================================================================
// TYPE EXPORTS
// ============================================================================

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

// ============================================================================
// STORE UTILITIES
// ============================================================================

/**
 * Get Store State
 * 
 * Purpose: Get the current state from the store
 * 
 * @returns Current Redux state
 */
export const getStoreState = (): RootState => store.getState();

/**
 * Dispatch Action
 * 
 * Purpose: Dispatch an action to the store
 * 
 * @param action - Redux action to dispatch
 * @returns Dispatched action result
 */
export const dispatchAction = (action: any) => store.dispatch(action);

/**
 * Subscribe to Store Changes
 * 
 * Purpose: Subscribe to store state changes
 * 
 * @param listener - Function to call when state changes
 * @returns Unsubscribe function
 */
export const subscribeToStore = (listener: () => void) => store.subscribe(listener);

/**
 * Clear Persisted State
 * 
 * Purpose: Clear all persisted state from AsyncStorage
 * 
 * @returns Promise that resolves when state is cleared
 */
export const clearPersistedState = async (): Promise<void> => {
  try {
    await persistor.purge();
    console.log('Persisted state cleared successfully');
  } catch (error) {
    console.error('Failed to clear persisted state:', error);
    throw error;
  }
};

/**
 * Get Persistence Status
 * 
 * Purpose: Get the current status of Redux Persist
 * 
 * @returns Persistence status object
 */
export const getPersistenceStatus = () => {
  return {
    isRehydrated: persistor.getState().bootstrapped,
  };
};

/*
 * End of File: index.ts
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */ 