/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

import axios from 'axios';
window.axios = axios;

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

// Ensure CSRF is sent even before the XSRF-TOKEN cookie exists.
// This is required for axios/Inertia POST requests like /login.
// const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
// if (csrfToken) {
//    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken;
// }

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 *
 * OPTIMIZACIÓN: Echo se inicializa de forma LAZY (solo cuando se necesita)
 * para evitar bloquear la carga inicial de la página con la conexión WebSocket.
 */

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;

// Variables de entorno para Pusher
const pusherKey = import.meta.env.VITE_PUSHER_APP_KEY;
const pusherCluster = import.meta.env.VITE_PUSHER_APP_CLUSTER;

/**
 * Inicializa Laravel Echo de forma lazy.
 * Solo se conecta al WebSocket cuando se llama esta función.
 * Retorna la instancia de Echo o null si no hay credenciales.
 */
export const initializeEcho = (): typeof window.Echo | null => {
    // Si ya está inicializado, retornar la instancia existente
    if (window.Echo) {
        return window.Echo;
    }

    // Verificar credenciales
    if (!pusherKey || !pusherCluster) {
        if (import.meta.env.DEV) {
            console.warn('⚠️ Laravel Echo no inicializado: Faltan credenciales de Pusher en .env');
        }
        return null;
    }

    try {
        // Solo habilitar logs de Pusher en desarrollo
        Pusher.logToConsole = import.meta.env.DEV;

        window.Echo = new Echo({
            broadcaster: 'pusher',
            key: pusherKey,
            cluster: pusherCluster,
            wsHost: import.meta.env.VITE_PUSHER_HOST || undefined,
            wsPort: import.meta.env.VITE_PUSHER_PORT ? parseInt(import.meta.env.VITE_PUSHER_PORT) : 80,
            wssPort: import.meta.env.VITE_PUSHER_PORT ? parseInt(import.meta.env.VITE_PUSHER_PORT) : 443,
            forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
            enabledTransports: ['ws', 'wss'],
            authEndpoint: '/broadcasting/auth',
            auth: {
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json',
                }
            }
        });

        if (import.meta.env.DEV) {
            console.log('✅ Laravel Echo inicializado correctamente (lazy)');
        }

        return window.Echo;
    } catch (error) {
        console.error('❌ Error al inicializar Laravel Echo:', error);
        return null;
    }
};

// Exportar información de configuración para debugging
export const hasEchoCredentials = (): boolean => {
    return Boolean(pusherKey && pusherCluster);
};