/**
 * CSRF Token Utility Functions
 * 
 * This module provides centralized CSRF token management for the application.
 * It ensures consistent token generation, storage, and retrieval across all components.
 */

// Configuration flag for CSRF token bypass (temporary for testing)
const CSRF_BYPASS_FOR_TESTING = false; // Set to true to disable CSRF tokens temporarily

/**
 * Generates a cryptographically secure CSRF token
 * @returns A 16-character hexadecimal string
 */
export const generateCSRFToken = (): string => {
  const array = new Uint32Array(8);
  window.crypto.getRandomValues(array);
  return Array.from(array, dec => ('0' + dec.toString(16)).slice(-2)).join('');
};

/**
 * Retrieves the current CSRF token from sessionStorage
 * @returns The CSRF token if it exists, null otherwise
 */
export const getCSRFToken = (): string | null => {
  return sessionStorage.getItem('csrf_token');
};

/**
 * Stores a CSRF token in sessionStorage
 * @param token The CSRF token to store
 */
export const setCSRFToken = (token: string): void => {
  sessionStorage.setItem('csrf_token', token);
};

/**
 * Generates and stores a new CSRF token
 * @returns The newly generated CSRF token
 */
export const generateAndStoreCSRFToken = (): string => {
  const token = generateCSRFToken();
  setCSRFToken(token);
  console.log('🔒 CSRF token generated and stored');
  return token;
};

/**
 * Adds CSRF token to request headers if available
 * @param headers Existing headers object
 * @returns Headers object with CSRF token added if available
 */
export const addCSRFTokenToHeaders = (headers: Record<string, string> = {}): Record<string, string> => {
  // Skip CSRF token if bypass is enabled
  if (CSRF_BYPASS_FOR_TESTING) {
    console.log('⚠️ CSRF token bypass enabled for testing');
    return headers;
  }

  const csrfToken = getCSRFToken();
  if (csrfToken) {
    headers['X-CSRF-Token'] = csrfToken;
    console.log('🔒 Using CSRF token:', csrfToken.substring(0, 10) + '...');
  } else {
    console.warn('⚠️ No CSRF token found in sessionStorage');
    console.log('🔍 Available sessionStorage keys:', Object.keys(sessionStorage));
  }
  return headers;
};

/**
 * Checks if a CSRF token exists in sessionStorage
 * @returns True if token exists, false otherwise
 */
export const hasCSRFToken = (): boolean => {
  return getCSRFToken() !== null;
};
