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

export const useAuthStore = defineStore('auth', () => {
    
    const router = useRouter();
    const route = useRoute();
    const noty = useNotificationsStore();
    const company = useCompanyStore();
    const loadStore = useLoadsStore();
    const vehiclesStore = useVehiclesStore();
    const sesion = ref('')
    const checking = ref(false);
    const authStatus = ref('checking');
    const token = ref('')
    const lang = ref('es');
    const user = ref(null);
    const publicNames = [
        'terms-conditions',
        'notice-privacy',
        'tracking-load',
        'faqs',
        'login',
        'register',
        'recovery',
        'register-company',
    ]

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


    const checkSession = async() => {
        const session = localStorage.getItem('session');
        authStatus.value = 'checking';
        if(session && !publicNames.includes(route.name)) {
            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;
                console.log(resp.data.user)
                localStorage.setItem('session', resp.data.session_token);
                localStorage.setItem('access', resp.data.accessToken);
                localStorage.setItem('id', resp.data.user.company._id);
                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 updateProfile = async(data) => {
        const response = await updateMyUserProfile(data);
        // console.log(response);
        if( response.msg === 'success') {
            user.value = response.data;
            return response;
        } else {
            return response;
        }
    }

    const logout = () => {
        localStorage.removeItem('access');
        localStorage.removeItem('id');
        localStorage.removeItem('session');

        sesion.value = '';
        token.value = '';
        user.value = null;
        checking.value = false;
        authStatus.value = 'checking'

        company.clear();
        loadStore.clear();
        vehiclesStore.clear();

        router.push({name: 'login'});
    }

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