/**
 * Utility functions for JWT token operations
 */

/**
 * Decodes a JWT token and returns the payload
 * @param token - The JWT token string
 * @returns The decoded payload or null if decoding fails
 */
export function decodeJWT(token: string): any | null {
  try {
    const base64Url = token.split('.')[1];
    if (!base64Url) return null;
    
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join('')
    );
    
    return JSON.parse(jsonPayload);
  } catch (error) {
    console.error('Error decoding JWT:', error);
    return null;
  }
}

/**
 * Gets the current user ID from the JWT token
 * @param accessToken - The JWT access token
 * @returns The user ID (from JWT sub field) or null if not available
 */
export function getUserIdFromToken(accessToken: string): number | null {
  try {
    if (!accessToken) {
      return null;
    }
    
    const payload = decodeJWT(accessToken);
    if (!payload || !payload.sub) {
      return null;
    }
    
    return typeof payload.sub === 'number' ? payload.sub : parseInt(payload.sub, 10);
  } catch (error) {
    console.error('Error getting user ID from token:', error);
    return null;
  }
}

/**
 * Gets the current user ID from the JWT token stored in user store
 * This function should be called from within a React component that has access to the store
 * @param userData - The user data from the store
 * @returns The user ID (from JWT sub field) or null if not available
 */
export function getCurrentUserId(userData?: { tokens?: { access?: string } }): number | null {
  try {
    if (!userData?.tokens?.access) {
      return null;
    }
    
    return getUserIdFromToken(userData.tokens.access);
  } catch (error) {
    console.error('Error getting current user ID:', error);
    return null;
  }
}

