import {useEntityManager} from "~/composables/data/useEntityManager";
import MyProfile from "~/models/Access/MyProfile";
import {useAccessProfileStore} from "~/stores/accessProfile";
import {useOrganizationProfileStore} from "~/stores/organizationProfile";

export const useRefreshProfile = () => {

    const accessProfileStore = useAccessProfileStore()
    const organizationProfileStore = useOrganizationProfileStore()
    const { em } = useEntityManager()

    const fetchProfile = async (accessId: number | null = null): Promise<MyProfile> => {
        if (accessId === null) {
            accessId = accessProfileStore.currentAccessId
        }

        return await em.fetch(MyProfile, accessId, true) as MyProfile
    }

    /**
     * Fetch the access profile and initiate the user profile and organization profile stores
     *
     * /!\ Server side only!
     *
     * @param accessId
     * @param bearer
     * @param switchId
     */
    const initiateProfile = async (accessId: number, bearer: string, switchId: number | null): Promise<void> => {
        accessProfileStore.$patch({
            bearer: bearer,
            id: accessId,
            switchId: switchId
        })

        const profile = await fetchProfile(accessId)

        // Sans le flush, on observe un bug non-expliqué au rechargement de la page en mode dev : la fonction save
        //  du repo de MyProfile ne fonctionne pas quand le plugin init.server.ts re-fetch le profil
        em.flush(MyProfile)

        accessProfileStore.initiateProfile(profile)
        organizationProfileStore.initiateProfile(profile.organization)
    }

    /**
     * Re-fetch the user profile and update the store
     */
    const refreshProfile = async (accessId: number | null = null) => {
        const profile = await fetchProfile(accessId)

        // Sans le flush, on observe un bug non-expliqué au rechargement de la page en mode dev : la fonction save
        //  du repo de MyProfile ne fonctionne pas quand le plugin init.server.ts re-fetch le profil
        em.flush(MyProfile)

        accessProfileStore.setProfile(profile)
        organizationProfileStore.setProfile(profile.organization)
    }

    return { initiateProfile, refreshProfile }
}
