import { ref, watch, toRaw, onMounted } from 'vue'

const config = ref()
let configResolve = null
const configPromise = new Promise((resolve) => {
    configResolve = resolve
})

export default () => {
    onMounted(async () => {
        if (config.value) {
            configResolve()
            return
        }
        config.value = await window.api.getConfig()
        configResolve()
    })

    watch(
        config,
        async (newValue) => {
            await window.api.setConfig(toRaw(newValue))
        },
        { deep: true },
    )

    const ensureConfig = async () => {
        if (config.value) return config.value
        return configPromise
    }

    const refreshConfig = async () => {
        config.value = await window.api.getConfig()
        configResolve()
    }

    return {
        config,
        ensureConfig,
        refreshConfig,
    }
}
