//* API TOKEN
  // DOM & Window control
    window.apiTokenReady = generateOrGetToken();

  // Session Interactions
    function logoutUser(event) {
        event.preventDefault();

        $.ajax({
            url: "/logout-harsi",
            method: "POST",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                'Authorization': 'Bearer ' + sessionStorage.getItem('api_access_token'),
                'X-Device-Id': getOrCreateDeviceId()
            },
            success: function () {
                sessionStorage.clear();
                window.location.href = '/';
            },
            error: function (err) {
                console.error("Error cerrando sesión:", err);
                alert('Error al cerrar sesión. Intenta de nuevo.');
            }
        });
    }

  // Token Management
    function generateOrGetToken() {
        return new Promise((resolve, reject) => {
            const storedToken = sessionStorage.getItem('api_access_token');

            if (storedToken) {
                setToken(storedToken);
                resolve(storedToken);
            } else {
                fetchNewToken().then(resolve).catch(reject);
            }
        });
    }

    function setToken(token) {
        $.ajaxSetup({
            headers: {
                'Authorization': 'Bearer ' + token
            }
        });
        sessionStorage.setItem('api_access_token', token);
    }

    function fetchNewToken() {
        const deviceId = getOrCreateDeviceId();

        return $.ajax({
            url: "/tokens/generate-api-token",
            method: 'GET',
            headers: {
                'X-Device-Id': deviceId
            }
        }).then(data => {
            const token = data.token;
            setToken(token);
            return token;
        });
    }

  // Support Functions
    // Internal
    function getOrCreateDeviceId() {
        let deviceId = sessionStorage.getItem('device_id');
            if (!deviceId) {
                deviceId = 'device-' + Math.random().toString(36).substr(2, 10);
                sessionStorage.setItem('device_id', deviceId);
            }

        return deviceId;
    }

    // Request
    window.apiGet = function(url, callback, data = null) {
        window.apiTokenReady.then(token => {
            $.ajax({
                url: url,
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                data: data || {},
                success: callback,
                error: function(err) {
                    if (err.status === 401) {
                        console.warn("Token expirado o inválido. Regenerando...");

                        // Remove actual Token
                        sessionStorage.removeItem('api_access_token');

                        // Regenerate Token
                        generateOrGetToken().then(newToken => {
                            window.apiGet(url, callback);
                        });
                    } else {
                        console.error("Error en apiGet:", err);
                    }
                }
            });
        });
    };

