import NotesAPI from '@/libs/core/NotesAPI.js'
import IpcAdapter from '@/libs/core/IpcAdapter.js'
import useConfig from '@/composables/useConfig.js'

// Singleton pattern to make sure only one instance of NotesAPI exists
let notesAPI = null
let initPromise = null

const generateEncryptionKey = () => {
    const array = new Uint8Array(32)
    crypto.getRandomValues(array)
    return Array.from(array)
        .map((b) => b.toString(16).padStart(2, '0'))
        .join('')
}

const createInstance = async () => {
    const { config, ensureConfig } = useConfig()
    await ensureConfig()

    let encryptionKey = config.value?.encryptionKey

    if (!encryptionKey) {
        encryptionKey = generateEncryptionKey()
        config.value.encryptionKey = encryptionKey
    }

    const adapter = new IpcAdapter()
    const api = new NotesAPI(adapter, encryptionKey)

    await api.init()

    return api
}

export const getNotesAPI = async () => {
    if (notesAPI) return notesAPI

    if (!initPromise) {
        initPromise = createInstance().then((api) => {
            notesAPI = api
            return api
        })
    }

    return initPromise
}
