import { defineStore } from 'pinia'

// @ts-ignore
export const useTempStore = defineStore('temp', () => {
    const auth = useAuthStore()

    const searchStrings = ref({})
    const filters = ref({})
    const columns = ref({})
    const pages = ref({})
    const settings = ref({})

    const storeTempConfig = async () => {
        const config = {
            searchStrings: searchStrings.value,
            columns: columns.value,
            pages: pages.value,
            settings: settings.value,
            filters: filters.value
        }

        await useNuxtApp().$api(`/api/profiles/${auth.profile.id}`, {
            method: 'PUT',
            body: { temp_config: config }
        })
    }

    function setStoredTempConfig(config) {
        searchStrings.value = config.searchStrings || {}
        columns.value = config.columns || {}
        pages.value = config.pages || {}
        settings.value = config.settings || {}
        filters.value = config.filters || {}
    }

    function modifySearchString(type, input) {
        searchStrings.value[type] = input
        storeTempConfig()
    }

    function clearSearchString(type) {
        searchStrings.value[type] = ""
        storeTempConfig()
    }

    function modifyFilter(domain, type, input) {
        if (!filters.value[domain]) filters.value[domain] = {}
        filters.value[domain][type] = input
        storeTempConfig()
    }

    function setFilters(domain, nextFilters) {
        filters.value[domain] = nextFilters
        if (!filters.value[domain] || Object.keys(filters.value[domain]).length === 0) {
            delete filters.value[domain]
        }
        storeTempConfig()
    }

    function clearFilter(domain, type) {
        if (!filters.value[domain]) return
        delete filters.value[domain][type]
        if (Object.keys(filters.value[domain]).length === 0) {
            delete filters.value[domain]
        }
        storeTempConfig()
    }

    function modifyColumns(type, input) {
        columns.value[type] = input
        storeTempConfig()
    }

    function modifyPages(type, input) {
        pages.value[type] = input
        storeTempConfig()
    }

    function modifySettings(type, input) {
        settings.value[type] = input
        storeTempConfig()
    }

    // Spezifisch für das Banking-Datum
    function modifyBankingPeriod(periodKey, range) {
        if (!settings.value['banking']) settings.value['banking'] = {}

        settings.value['banking'].periodKey = periodKey
        settings.value['banking'].range = range

        storeTempConfig()
    }

    return {
        setStoredTempConfig,
        searchStrings,
        modifySearchString,
        clearSearchString,
        filters,
        modifyFilter,
        setFilters,
        clearFilter,
        columns,
        modifyColumns,
        modifyPages,
        pages,
        modifySettings,
        modifyBankingPeriod, // Neue Funktion exportiert
        settings
    }
})
