<script setup>
import { useAuth } from '@websanova/vue-auth/src/v3.js';
import axios from 'axios';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { msalInstance } from './MsalConfig';

const router = useRouter();
const auth = useAuth();
const message = ref('');
const visible = ref(false);

onMounted(async () => {
    console.log('[Callback] Mounted on callback');
    try {
        await msalInstance.initialize();
        console.log('[Callback] After initialize on callback');
    } catch (e) {
        console.error('[Callback] Errore durante initialize MSAL:', e);
        message.value = "Errore durante l'inizializzazione di MSAL.";
        visible.value = true;
        return;
    }

    let response;
    try {
        response = await msalInstance.handleRedirectPromise();
        console.log('[Callback] handleRedirectPromise response:', response);
    } catch (e) {
        console.error('[Callback] Errore in handleRedirectPromise:', e);
        message.value = 'Errore durante la gestione del redirect.';
        visible.value = true;
        return;
    }

    if (response && response.accessToken) {
        message.value = 'Logging in to the application...';
        console.log('[Callback] AccessToken presente:', response.accessToken);
        console.log('[Callback] Account info:', response.account);
        localStorage.setItem('msalUser', JSON.stringify(response.account));

        try {
            console.log('[Callback] Chiamata a /msauth/exchange con accessToken...');
            const res = await axios.post(
                '/msauth/exchange',
                {},
                {
                    headers: { Authorization: `Bearer ${response.accessToken}` }
                }
            );
            console.log('[Callback] Risposta da /msauth/exchange:', res);

            if (res.data.token) {
                console.log('[Callback] Token backend ricevuto:', res.data.token);
                auth.token(null, res.data.token, false);
                try {
                    console.log('[Callback] Chiamata a auth.fetch()...');
                    const userResponse = await auth.fetch();
                    console.log('[Callback] Risposta user fetch:', userResponse);
                    console.log('[Callback] userResponse.data:', userResponse.data);
                    console.log('[Callback] userResponse.data.data:', userResponse.data.data);

                    if (!userResponse.data.data.selectedProject) {
                        console.log('[Callback] Nessun progetto selezionato, redirect a projects-list');
                        router.push({ name: 'projects-list' });
                    } else {
                        console.log('[Callback] Progetto selezionato, redirect a scenario-list');
                        router.push({ name: 'scenario-list' });
                    }
                } catch (fetchErr) {
                    console.error('[Callback] Errore su fetch user dopo token exchange:', fetchErr);
                    message.value = 'User not configured for this application. Contact the administrator for details.';
                    visible.value = true;
                }
            } else {
                message.value = 'User not configured for this application. Contact the administrator for details.';
                console.error('[Callback] Nessun token ricevuto dal backend:', res.data);
            }
        } catch (error) {
            console.error('[Callback] Error on token exchange:', error.response ? error.response.data : error);
            message.value = 'An error occurred during the token exchange. Please try again.';
            visible.value = true;
        }
    } else {
        console.error('[Callback] Invalid response o access token mancante:', response);
        message.value = 'Authentication failed. Please log in again.';
        visible.value = true;
    }
});
</script>

<template>
    <div>{{ message }}</div>
</template>
