import UnauthorizedError from "~/services/error/UnauthorizedError";
import {useRedirect} from "~/composables/utils/useRedirect";
import {useRefreshProfile} from "~/composables/data/useRefreshProfile";
import type {CookieRef} from "#app";

export default defineNuxtPlugin(async () => {
    const { redirectToLogout } = useRedirect()

    const bearer: CookieRef<string | null> = useCookie('BEARER') ?? null
    let accessCookieId: CookieRef<string | null> = useCookie('AccessId') ?? null
    const switchId: CookieRef<string | null> = useCookie('SwitchAccessId') ?? null

    if (accessCookieId.value === null || Number.isNaN(accessCookieId.value)) {
        redirectToLogout()
        return
    }

    const accessId: number = parseInt(accessCookieId.value)
    if (isNaN(accessId)) {
        redirectToLogout()
        return
    }

    const { initiateProfile } = useRefreshProfile()

    try {
        await initiateProfile(
            accessId,
            bearer.value ?? '',
            switchId.value !== null ? parseInt(switchId.value) : null
        )

    } catch (error) {
        if (error instanceof UnauthorizedError) {
            redirectToLogout()
        } else {
            throw error
        }
    }
})
