import {defineNuxtPlugin, useCookie} from "nuxt/app";
import {useAccessProfileStore} from "~/stores/accessProfile";
import {useEntityManager} from "~/composables/data/useEntityManager";
import UnauthorizedError from "~/services/error/UnauthorizedError";
import {useRedirectToLogout} from "~/composables/utils/useRedirectToLogout";

export default defineNuxtPlugin(async () => {
    const redirectToLogout = useRedirectToLogout()

    const bearer = useCookie('BEARER')
    const accessId = useCookie('AccessId')

    const accessProfile = useAccessProfileStore()

    if (accessId.value === null) {
        redirectToLogout()
        return
    }

    accessProfile.$patch({
        bearer: bearer.value,
        id: parseInt(accessId.value)
    })

    const {em} = useEntityManager()

    try {
        await em.refreshProfile(parseInt(accessId.value))
    } catch (error) {
        if (error instanceof UnauthorizedError) {
            redirectToLogout()
        } else {
            throw error
        }
    }
})
