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

export const useAuthStore = defineStore('auth', () => {
    const user = ref<User>();
    const authError = ref("");
    const isAuthorizedUser = computed(() => CAN_APPROVE_PAY_PERIODS.includes(user.value?.role ?? 'GUEST'));
    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;
    };

    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, isAuthorizedUser, login, oidcLogin, logout, getProfile };
});

