/**
 * User Data Cache Management
 * 
 * Centralized user data storage using sessionStorage for security.
 * sessionStorage is cleared when the browser tab/window closes, making it more secure than localStorage.
 * 
 * Flow:
 * 1. Login → Authentication hooks (useAuthentication.ts, useUsers.ts) set user data
 * 2. Components/Checkers → Read user data from cache
 * 3. Logout → Clear user data cache
 */

const USER_CACHE_KEY = '__user_cache__';

export interface CachedUserData {
    id: string;
    username: string;
    email: string;
    fullName: string;
    privilege?: string; // Deprecated - use roleLabels instead
    roleLabels?: string[]; // Array of role labels from backend (e.g., ["user"])
    // mandateId entfernt - User gehört keinem Mandanten direkt an
    // Stattdessen hat er Zugriff auf Feature-Instanzen (siehe featureStore)
    isSysAdmin?: boolean; // System-Administrator Flag
    language: string;
    enabled: boolean;
    authenticationAuthority: string;
}

/**
 * Set user data in sessionStorage cache
 * Called by authentication hooks after successful login
 */
export const setUserDataCache = (userData: CachedUserData): void => {
    if (userData) {
        // Always cache user data - permissions are checked via RBAC API, not client-side
        // roleLabels/privilege are optional metadata, not required for app functionality
        try {
            sessionStorage.setItem(USER_CACHE_KEY, JSON.stringify(userData));
        } catch (error) {
            console.error('Failed to cache user data:', error);
        }
    }
};

/**
 * Get user data from sessionStorage cache
 * Called by components and privilege checkers
 */
export const getUserDataCache = (): CachedUserData | null => {
    try {
        const cached = sessionStorage.getItem(USER_CACHE_KEY);
        if (cached) {
            return JSON.parse(cached);
        }
    } catch (error) {
        console.error('Failed to parse user data from cache:', error);
        // Clear corrupted data
        sessionStorage.removeItem(USER_CACHE_KEY);
    }
    return null;
};

/**
 * Clear user data cache
 * Called on logout
 */
export const clearUserDataCache = (): void => {
    sessionStorage.removeItem(USER_CACHE_KEY);
};

