/*
 * Runtime Web – Unified Serverless Framework for Full-Stack TypeScript Applications
 * Documentation: https://runtimeweb.com/docs/getting-started
 *
 * @template: ai-chat
 */

/**
 * Session Manager Service
 *
 * Manages session identification and user preferences for the AI Chat application.
 * Handles localStorage persistence for session IDs and behavior mode preferences.
 *
 * SSR Safety: All localStorage operations are guarded with `typeof window !== 'undefined'`
 * checks to ensure compatibility with server-side rendering environments.
 *
 * @module services/session-manager
 */

/** localStorage key for session ID persistence */
const SESSION_KEY = 'ai-chat-session-id';

/** localStorage key for behavior mode preference persistence */
const BEHAVIOR_KEY = 'ai-chat-behavior-mode';

/**
 * SessionManager handles session identification and preference persistence.
 *
 * Features:
 * - Generates unique session IDs with timestamp + random pattern
 * - Persists session IDs to localStorage for cross-reload continuity
 * - Manages behavior mode preferences (precise/balanced/creative)
 * - SSR-safe with window existence checks
 *
 * @example
 * ```typescript
 * import { sessionManager } from './services/session-manager.service';
 *
 * // Get or create session ID
 * const sessionId = sessionManager.getSessionId();
 *
 * // Manage behavior preferences
 * sessionManager.setBehaviorMode('creative');
 * const mode = sessionManager.getBehaviorMode(); // 'creative'
 * ```
 */
export class SessionManager {
    /** Cached session ID to avoid repeated localStorage reads */
    private sessionId: string | null = null;

    /**
     * Gets or creates a session ID, persisting to localStorage.
     *
     * Behavior:
     * 1. Returns cached sessionId if available (in-memory)
     * 2. Attempts to retrieve from localStorage if in browser environment
     * 3. Generates new sessionId if none exists
     * 4. Persists new sessionId to localStorage
     *
     * @returns The session ID string in format `session-{timestamp}-{random}`
     *
     * @example
     * ```typescript
     * const sessionId = sessionManager.getSessionId();
     * // Returns: 'session-m1abc2d-e3f4g5h6i7j8k'
     * ```
     */
    getSessionId(): string {
        if (this.sessionId) {
            return this.sessionId;
        }

        // Try to get from localStorage (browser only)
        if (typeof window !== 'undefined') {
            const stored = localStorage.getItem(SESSION_KEY);
            if (stored) {
                this.sessionId = stored;
                return stored;
            }
        }

        // Generate new session ID
        this.sessionId = this.generateSessionId();

        // Persist to localStorage (browser only)
        if (typeof window !== 'undefined') {
            localStorage.setItem(SESSION_KEY, this.sessionId);
        }

        return this.sessionId;
    }

    /**
     * Generates a unique session ID.
     *
     * Format: `session-{timestamp}-{random}`
     * - timestamp: Base36 encoded Date.now() for uniqueness and compactness
     * - random: Base36 encoded random number for collision avoidance
     *
     * @returns A unique session ID string
     *
     * @example
     * ```typescript
     * // Internal method, called by getSessionId()
     * // Generates: 'session-m1abc2d-e3f4g5h6i7j8k'
     * ```
     */
    private generateSessionId(): string {
        const timestamp = Date.now().toString(36);
        const random = Math.random().toString(36).substring(2, 15);
        return `session-${timestamp}-${random}`;
    }

    /**
     * Gets the stored behavior mode preference.
     *
     * @returns The stored behavior mode, or 'balanced' as default
     *
     * @example
     * ```typescript
     * const mode = sessionManager.getBehaviorMode();
     * // Returns: 'balanced' (default) or stored preference
     * ```
     */
    getBehaviorMode(): string {
        if (typeof window !== 'undefined') {
            return localStorage.getItem(BEHAVIOR_KEY) || 'balanced';
        }
        return 'balanced';
    }

    /**
     * Stores the behavior mode preference.
     *
     * @param mode - The behavior mode to store ('precise' | 'balanced' | 'creative')
     *
     * @example
     * ```typescript
     * sessionManager.setBehaviorMode('creative');
     * ```
     */
    setBehaviorMode(mode: string): void {
        if (typeof window !== 'undefined') {
            localStorage.setItem(BEHAVIOR_KEY, mode);
        }
    }

    /**
     * Clears the current session and generates a new one.
     *
     * This removes the session ID from localStorage and clears the cached value,
     * allowing a fresh session to be created on the next getSessionId() call.
     *
     * @example
     * ```typescript
     * sessionManager.clearSession();
     * const newSessionId = sessionManager.getSessionId(); // New session
     * ```
     */
    clearSession(): void {
        this.sessionId = null;
        if (typeof window !== 'undefined') {
            localStorage.removeItem(SESSION_KEY);
        }
    }
}

/**
 * Singleton instance of SessionManager.
 *
 * Use this exported instance for consistent session management
 * across the application.
 *
 * @example
 * ```typescript
 * import { sessionManager } from './services/session-manager.service';
 *
 * const sessionId = sessionManager.getSessionId();
 * ```
 */
export const sessionManager = new SessionManager();
