import { defineStore } from "pinia";
import { ref, onMounted } from "vue";
import { useRouter } from 'vue-router';
import { renewToken } from '../services/auth';
import {useNotificationsStore} from './notifications';
import {useCompanyStore} from './company';

export const useAuthStore = defineStore('auth', () => {
    
    const router = useRouter();
    const noty = useNotificationsStore();
    const company = useCompanyStore();
    const sesion = ref('')
    const checking = ref(false);
    const authStatus = ref('checking');
    const token = ref('')
    const user = ref(null)

    onMounted( async() => {
        checkSession();
    });

    const checkSession = async() => {
        const session = localStorage.getItem('session');
        authStatus.value = 'checking';
        if(session) {
            checking.value = true;
            const resp = await renewToken();
            if(resp.msg === 'success') {
                user.value = resp.data.user;
                sesion.value = resp.data.session_token;
                token.value = resp.data.accessToken;
                localStorage.setItem('session', resp.data.session_token);
                localStorage.setItem('access', resp.data.accessToken);
                localStorage.setItem('id', resp.data.user.company);
                checking.value = false;
            } else {
                noty.show = true;
                noty.text = 'Sesión ha expirado, ingresa nuevamente';
                noty.error = true;
                checking.value = false;
                router.push({name: 'login'});
            }
        }
        authStatus.value = 'completed';
    }

    const authenticationPromise = new Promise((resolve) => {
      onMounted(() => {
        resolve('success');
      });
    });

    const logout = () => {
        console.log('logoo....');
        sesion.value = '';
        token.value = '';
        company.clear();
        user.value = null;
        console.log(company.company);
        localStorage.removeItem('access');
        localStorage.removeItem('id');
        localStorage.removeItem('session');
        router.push({name: 'login'});
    }

    return {
        sesion,
        logout,
        token,
        user,
        checking,
        authStatus,
        checkSession,
        authenticationPromise
    }
});