async function redirectToKeycloak() {
    if (!sessionStorage.getItem('access_token')) {
        const params = new URLSearchParams(window.location.search);
        const code = params.get('code');
        if (code) {
            exchangeCodeForToken(code);
            return;
        }
        const keycloakAuthUrl = 'http://10.6.71.74:30904/realms/NTN-Realm/protocol/openid-connect/auth?response_type=code&client_id=node-red-ntn&redirect_uri=http://10.6.71.74:30955/ui&scope=openid';

        console.log('No hay code, redirigiendo a:', keycloakAuthUrl);
        window.location.href = keycloakAuthUrl;
    } else {
        console.log('Token encontrado, no redirigiendo.');
    }
}


async function exchangeCodeForToken(code) {
    const tokenEndpoint = 'http://10.6.71.74:30904/realms/NTN-Realm/protocol/openid-connect/token';
    const params = new URLSearchParams();
    params.append('grant_type', 'authorization_code');
    params.append('client_id', 'node-red-ntn');
    params.append('code', code);
    params.append('redirect_uri', 'http://10.6.71.74:30955/ui');
    params.append('client_secret', 'vJc74yztMzbXGdHUVjjAAdH5RlGULrbK');

    try {
        const response = await fetch(tokenEndpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params.toString(),
        });
        console.log(response);
        if (response.ok) {
            const data = await response.json();
            sessionStorage.setItem('id_token', data.id_token);
            sessionStorage.setItem('access_token', data.access_token);
            sessionStorage.setItem('refresh_token', data.refresh_token);
            decodeToken(data.access_token);

            // Redirige a la UI principal
            window.location.href = 'http://10.6.71.74:30955/ui';
        } else {
            const errorData = await response.json();
            console.error('Error al intercambiar el código por un token', response.status, response.statusText, errorData);
        }
    } catch (error) {
        console.error('Error en la solicitud de token', error);
    }
}
if (!sessionStorage.getItem('access_token')) {
    const params = new URLSearchParams(window.location.search);
    const code = params.get('code');
    if (params.get('error')) {
        console.error('Error durante la autenticación en Keycloak:', params.get('error'));
    }
    if (!code) {
        // Llamar a la función directamente
        redirectToKeycloak();
    } else {
        exchangeCodeForToken(code);
    }
} else {
    let accessToken = decodeToken(sessionStorage.getItem('access_token'));
    let refreshToken = decodeToken(sessionStorage.getItem('refresh_token'));
    let idToken = decodeToken(sessionStorage.getItem('id_token'));
    console.log('Access Token :' + accessToken);
    console.log('Refresh Token :' + refreshToken);
    console.log('Id token:  ' + idToken);
    await sendDecodedToken(accessToken);
}

/**
 *      AUXILIARY FUNCTIONS
 */

function decodeToken(token) {
    const parts = token.split('.');

    if (parts.length !== 3) {
        console.error('JWT token format inválido');
        return;
    }

    const payload = JSON.parse(atob(base64UrlDecode(parts[1])));
    return (payload);
}

function base64UrlDecode(str) {
    str = str.replace(/-/g, '+').replace(/_/g, '/');
    switch (str.length % 4) {
        case 2: str += '=='; break;
        case 3: str += '='; break;
    }
    return str;
}


async function sendDecodedToken(userData) {

    const { given_name, email } = userData;
    const queryData = { given_name, email };

    // Enviar una solicitud POST
    fetch("/iduser", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"

        },
        body: JSON.stringify(queryData)
    })
        .then((response) => {

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();

        })
        .then(data => {
            if (data && Object.keys(data).length > 0) {
                console.log("Respuesta del servidor:", data);
            } else {
                console.log("La respuesta está vacía.");
            }
        })
        .catch(error => {
            console.error("Error al enviar la solicitud:", error);
        });
}



// Main logic to handle token or redirect flow
if (!sessionStorage.getItem('access_token')) {
    const params = new URLSearchParams(window.location.search);
    const code = params.get('code');

    if (!code) {
        redirectToKeycloak();
    } else {
        exchangeCodeForToken(code);
    }
} else {
    const token = decodeToken(sessionStorage.getItem('access_token'));
    sendDecodedToken(token);
}
