import {
  authenticateCredentialsThunk,
  selectIsAuthenticated,
  selectIsLoading,
  selectApplicationId,
  selectSecret,
  setUnauthorized
} from 'store/slices/Authentication.slice';
import {Middleware} from '@reduxjs/toolkit';

export const authenticateRequestMiddleware: Middleware = store => next => async action => {
  const state = store.getState();
  const isAuthenticated = selectIsAuthenticated(state);
  const isLoading = selectIsLoading(state);
  const applicationId = selectApplicationId(state);
  const secret = selectSecret(state);

  console.log(
    '[authenticateRequestMiddleware] action [%o] isAuthenticated [%o] isLoading [%o] applicationId [%o] secret [%o]',
    action,
    isAuthenticated,
    isLoading,
    applicationId,
    secret
  );

  // Skip authentication middleware for authentication-related actions

  if (
    typeof action === 'object' &&
    action !== null &&
    'type' in action &&
    typeof (action as {type: string}).type === 'string' &&
    (action as {type: string}).type.startsWith('authentication/')
  ) {
    return next(action);
  }

  // If already authenticated, proceed normally
  if (isAuthenticated) {
    return next(action);
  }

  // If currently loading, wait for it to complete
  if (isLoading) {
    return next(action);
  }

  // If no credentials, set unauthorized
  if (!applicationId || !secret) {
    console.log('[authenticateRequest] No credentials available, proceeding with action');
    return next(setUnauthorized());
  }

  // We have credentials but are not authenticated, try to authenticate
  try {
    console.log('[authenticateRequest] Attempting auto-authentication');
    // Use the Redux thunk to properly update the state
    const authResult = await store.dispatch(authenticateCredentialsThunk({ applicationId, secret }) as any);

    if (authResult.type.endsWith('/rejected') || authResult.payload === 'Authentication failed') {
      console.log('[authenticateRequest] Authentication failed');
      return next(setUnauthorized());
    }
    
    console.log('[authenticateRequest] Auto-authentication successful, proceeding with action');
    return next(action);
  } catch (error) {
    console.error('[authenticateRequest] Auto-authentication failed:', error);
    return next(setUnauthorized());
  }
};
