import { defineStore } from "pinia"
import OneSignal from "onesignal-cordova-plugin"
import { Capacitor } from "@capacitor/core"

export const useProfileStore = defineStore("profile", () => {
    const auth = useAuthStore()
    const dataStore = useDataStore()
    const toast = useToast()
    const tempStore = useTempStore()

    const loaded = ref(false)
    const showProfileSelection = ref(false)

    const ownTenant = ref({
        calendarConfig: { eventTypes: [] },
        timeConfig: { timeTypes: [] },
        tags: { documents: [], products: [] },
        measures: []
    })

    const profiles = ref([])
    const ownProfiles = ref([])
    const activeProfile = ref(null)
    const tenants = ref([])
    const currentTenant = ref(null)

    const syncFromAuth = () => {
        currentTenant.value = auth.activeTenant || null
        activeProfile.value = auth.profile || null
        tenants.value = auth.tenants || []
    }

    async function initializeData() {
        await auth.fetchMe()
        syncFromAuth()

        if (activeProfile.value?.temp_config) {
            tempStore.setStoredTempConfig(activeProfile.value.temp_config)
        }

        if (currentTenant.value) {
            await fetchData()
            await dataStore.fetchData()

            if (Capacitor.getPlatform() === "ios" && activeProfile.value?.user_id) {
                OneSignal.initialize("1295d5ff-28f8-46a6-9c62-fe5d090016d7")
                OneSignal.Location.setShared(false)
                OneSignal.Notifications.requestPermission()
                OneSignal.login(activeProfile.value.user_id)
            }
        } else {
            toast.add({ title: "Kein aktiver Tenant", color: "orange" })
            showProfileSelection.value = true
        }
    }

    async function changeProfile(newActiveTenantId) {
        loaded.value = false
        await auth.switchTenant(String(newActiveTenantId))
    }

    async function fetchData() {
        await fetchOwnProfiles()
        await fetchProfiles()
        await fetchTenants()
        await fetchOwnTenant()
        loaded.value = true
    }

    function clearStore() {
        loaded.value = false
        ownTenant.value = {}
        profiles.value = []
        ownProfiles.value = []
        tenants.value = []
    }

    async function fetchOwnTenant() {
        syncFromAuth()
        try {
            const tenant = await useNuxtApp().$api("/api/tenant")
            if (tenant) {
                ownTenant.value = tenant
                auth.activeTenantData = tenant
                return
            }
        } catch (e) {
        }

        ownTenant.value = auth.activeTenantData || ownTenant.value
    }

    async function fetchProfiles() {
        try {
            const res = await useNuxtApp().$api("/api/tenant/profiles")
            profiles.value = res?.data || []
        } catch (e) {
            profiles.value = activeProfile.value ? [activeProfile.value] : []
        }
    }

    async function fetchOwnProfiles() {
        ownProfiles.value = profiles.value
    }

    async function fetchTenants() {
        syncFromAuth()
    }

    const getOwnProfile = computed(() => {
        return activeProfile.value
    })

    const getProfileById = computed(() => (itemId) => {
        return profiles.value.find((item) => item.id === itemId || item.user_id === itemId)
    })

    return {
        currentTenant,
        loaded,
        showProfileSelection,
        ownTenant,
        initializeData,
        changeProfile,
        profiles,
        ownProfiles,
        activeProfile,
        tenants,
        fetchData,
        clearStore,
        fetchOwnTenant,
        getOwnProfile,
        getProfileById
    }
})
