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

/**
 * useSession Hook
 *
 * React hook for accessing the session ID in a SSR-safe manner.
 * Retrieves the session ID from SessionManager only in browser environments,
 * ensuring compatibility with server-side rendering.
 *
 * @module hooks/useSession
 */

import { useState, useEffect } from 'react';
import { sessionManager } from '../services';

/**
 * Return type for the useSession hook.
 */
export interface UseSessionReturn {
    /** The current session ID, empty string during SSR or before hydration */
    sessionId: string;
    /** Clears the current session and generates a new one */
    clearSession: () => void;
}

/**
 * Hook for accessing the session ID in a SSR-safe manner.
 *
 * This hook ensures that localStorage access only occurs in browser environments,
 * preventing hydration mismatches and SSR errors. The sessionId is initialized
 * as an empty string and populated after the component mounts.
 *
 * @returns An object containing the sessionId
 *
 * @example
 * ```typescript
 * import { useSession } from '../hooks/useSession';
 *
 * function ChatPage() {
 *   const { sessionId } = useSession();
 *
 *   // sessionId is empty during SSR, populated after mount
 *   if (!sessionId) {
 *     return <div>Loading session...</div>;
 *   }
 *
 *   return <Chat sessionId={sessionId} />;
 * }
 * ```
 *
 * **Validates: Requirements 5.1, 5.2**
 */
export function useSession(): UseSessionReturn {
    const [sessionId, setSessionId] = useState<string>('');

    useEffect(() => {
        // Only access sessionManager in browser environment
        // This check is redundant since useEffect only runs client-side,
        // but kept for explicit SSR safety documentation
        if (typeof window !== 'undefined') {
            setSessionId(sessionManager.getSessionId());
        }
    }, []);

    const clearSession = () => {
        if (typeof window !== 'undefined') {
            sessionManager.clearSession();
            setSessionId(sessionManager.getSessionId());
        }
    };

    return { sessionId, clearSession };
}
