<template>
    <DefaultSplash width="600px;">
      
            <h1><Icon spin-pulse icon="fa-solid fa-spinner"/> Connexion en cours</h1>
            <p>Vous allez être redirigé vers l'application.</p>
            <div class="info">
                 <p class="second">Session : {{ loginStore.session }}</p>
                 <p class="second">Auth_Code : {{ route.query.code }}</p>
            </div>
           
      
    </DefaultSplash>    
</template>
<script setup>
import DefaultSplash from '@/components/UI/DefaultSplash.vue';
import { useLoginStore } from '@/stores/loginStore';
import { useRoute, useRouter } from 'vue-router';
import {socket} from '@/socket.js';

const loginStore = useLoginStore();
const route = useRoute();
const router = useRouter();

if(!loginStore.session) {
    router.push("/login?error=" + encodeURIComponent("Session expirée ou non valide"));
}

if(!route.query.code) {
    if(route.query.error) {
        router.push("/login?error=" + encodeURIComponent("Connexion refusée par l'utilisateur"));
    } else {
        // If no error is specified, redirect to login with a generic error message
        router.push("/login?error=" + encodeURIComponent("Code d'authentification Discord manquant"));
    }
} else {
    // Edit socket auth
    socket.auth = {
        sessionId: loginStore.session,
        auth_code: route.query.code
    };
    socket.connect();
}

socket.on("NEW_TOKEN", (token) => {
    loginStore.setToken(token);
    loginStore.setSession(null)
    router.push("/");
}); 


socket.on("error", () => {
    router.push("/login?error=" + encodeURIComponent("Déconnexion du serveur lors de la connexion"));
});
socket.on("disconnect", () => {
   router.push("/login?error=" + encodeURIComponent("Erreur lors de l'authentification, veuillez réessayer"));
}); 
socket.on("connect_error", (error) => {
    router.push("/login?error=" + encodeURIComponent("Erreur de connexion au serveur : " + error.message));
});

socket.on("NEW_SESSION", (data) => {
    console.log("Nouvelle session reçue :", data);
    loginStore.setSession(data);   
});

</script>
<style scoped>
.second {
    color: var(--text-secondary);
    font-size: 12px;;
    word-break: break-all;
}

.info p {
    margin: 0;
    padding: 0;
}

.info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: -10px;
}
</style>