import { ref } from "vue";
import { Notify } from "quasar";
import { defineStore } from "pinia";
import { AuthService } from "../modules/auth/services/services-auth";
import { useRouter } from "vue-router";
import type { User } from "src/modules/shared/models/user.models";

export const useAuthStore = defineStore('auth', () => {
    const user = ref<User>();
    const authError = ref("");
    const router = useRouter();

    const login = () => {
        //TODO: manage customer login process
    };

    const oidcLogin = () => {
        window.addEventListener('message', (event) => {
            void handleAuthMessage(event);
        });

        const oidc_popup = window.open(`${import.meta.env.VITE_TARGO_BACKEND_URL}auth/v1/login`, 'authPopup', 'width=600,height=800');

        if (!oidc_popup)
            Notify.create({
                message: "You have popups blocked on this website!",
                color: 'negative',
                textColor: 'white',
            });
    };

    const logout = () => {
        user.value = undefined;
        AuthService.logout();
        const logout_popup = window.open('https://auth.targo.ca/application/o/montargo/end-session/', 'logoutPopup', 'width=200,height=200');
        
        setInterval(() => logout_popup?.close(), 2000);
    };

    const handleAuthMessage = async (event: MessageEvent) => {
        if (event.data.type === 'authSuccess') {
            try {
                await getProfile();
                await router.push('/');
            } catch (error) {
                console.error('failed to login: ', error);
            }
        } else {
            Notify.create({
                message: "You have popups blocked on this website!",
                color: 'negative',
                textColor: 'white',
            });
        }
    };

    const getProfile = async (): Promise<{ status: number, message: string }> => {
        try {
            const new_user = await AuthService.getProfile();
            user.value = new_user;
            return { status: 200, message: 'profile retrieved successfully' };
        } catch (error) {
            console.error('error while retrieving profile: ', error);
        }
        return { status: 400, message: 'unknown error occured' };
    }

    return {
        user,
        authError,
        login,
        oidcLogin,
        logout,
        getProfile
    };
});

