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')
    let accessCookieId = useCookie('AccessId')
    const switchId = useCookie('SwitchAccessId')

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

    const accessId: number = parseInt(accessCookieId.value)

    const accessProfile = useAccessProfileStore()

    accessProfile.$patch({
        bearer: bearer.value,
        id: accessId,
        switchId: switchId.value !== null ? parseInt(switchId.value) : null
    })

    const {em} = useEntityManager()

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