// Token validation caching module

// Cache for token validation to reduce API calls
const tokenValidationCache = {
  lastValidated: 0,
  token: null,
  isValid: false,
  retryAfter: 0 // Timestamp when to retry after rate limit
};

// Increased token validation cache duration (30 minutes instead of 5)
const TOKEN_VALIDATION_CACHE_DURATION = 1 * 60 * 1000; // 30 minutes in milliseconds

// Rate limiting parameters - significantly reduced
const RATE_LIMIT_BACKOFF = 1000; // 1 second backoff after rate limit (reduced from 1 minute)

/**
 * Validates a token with caching to reduce API calls
 * @param {string} token - The token to validate
 * @param {boolean} forceRefresh - Whether to force a refresh of the cache
 * @returns {Promise<boolean|null>} - true if valid, false if invalid, null if error
 */
async function validateTokenWithCache(token, forceRefresh = true) {
  if (!token || token.trim() === '') {
    console.error('Empty token provided to validateTokenWithCache');
    return false;
  }

  const now = Date.now();
  
  // Check if we're in a rate limit cooldown period
  if (tokenValidationCache.retryAfter > now) {
    console.log(`Rate limit cooldown active. Try again in ${Math.ceil((tokenValidationCache.retryAfter - now) / 1000)} seconds`);
    // Return the cached result if available, otherwise null
    return tokenValidationCache.token === token ? tokenValidationCache.isValid : null;
  }
  
  // If we have a cached result for this token and it's not expired, use it
  if (
    !forceRefresh &&
    tokenValidationCache.token === token && 
    tokenValidationCache.lastValidated > 0 && 
    (now - tokenValidationCache.lastValidated) < TOKEN_VALIDATION_CACHE_DURATION
  ) {
    console.log('Using cached token validation result');
    return tokenValidationCache.isValid;
  }
  
  // Otherwise, perform actual validation
  console.log('Performing token validation check (cache expired or not available)');
  try {
    // Define the API URL
    const apiUrl = 'https://sharegift.shop/ShareGiftBot/extention/token_api.php?action=validate';
    
    // Create form data for the POST request
    const formData = new FormData();
    formData.append("token", token.trim() + "/new");
    
    // Make the API request with a reduced timeout (5 seconds instead of 10)
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000); // Increased to 10 second timeout
    
    const response = await fetch(apiUrl, {
      method: 'POST',
      body: formData,
      signal: controller.signal
    });
    
    clearTimeout(timeoutId);
    
    // Handle rate limiting (429 Too Many Requests)
    if (response.status === 429) {
      console.log('Rate limit exceeded. Implementing cooldown period.');
      // Set retry timestamp to current time plus backoff period
      tokenValidationCache.retryAfter = now + RATE_LIMIT_BACKOFF;
      
      // If we have a previous validation result for this token, use it
      if (tokenValidationCache.token === token && tokenValidationCache.lastValidated > 0) {
        console.log('Using previous validation result during rate limit cooldown');
        return tokenValidationCache.isValid;
      }
      
      // Otherwise, we can't validate right now
      return null;
    }
    
    if (!response.ok) {
      throw new Error('API request failed with status: ' + response.status);
    }
    
    const responseData = await response.json();
    
    // Update cache
    tokenValidationCache.lastValidated = now;
    tokenValidationCache.token = token;
    tokenValidationCache.isValid = responseData.success;
    tokenValidationCache.retryAfter = 0; // Reset any rate limit cooldown
    
    return responseData.success;
  } catch (error) {
    console.error('Error during token validation:', error);
    // Check if this is a rate limit error from the error message
    if (error.message && error.message.includes('429')) {
      console.log('Rate limit error detected from error message');
      tokenValidationCache.retryAfter = now + RATE_LIMIT_BACKOFF;
    }
    // Don't update cache on error to force retry next time
    return null; // Return null to indicate error
  }
}

/**
 * Invalidates the token cache
 */
function invalidateTokenCache() {
  tokenValidationCache.lastValidated = 0;
  tokenValidationCache.token = null;
  tokenValidationCache.isValid = false;
  tokenValidationCache.retryAfter = 0; // Reset retry timer
}

// Export the functions
export default {
  validateTokenWithCache,
  invalidateTokenCache
};
