import type { Pinia } from 'pinia'
import { createPinia } from 'pinia'
import { createPersistedState } from 'pinia-plugin-persistedstate'
import type { App } from 'vue'

const store: Pinia = createPinia()
const setupStore = (app: App<Element>) => {
  store.use(createPersistedState({
    key: id => `__neosjs_persisted__${id}`,
    storage: window.localStorage,
    debug: import.meta.env.DEV
  }))
  app.use(store)
}

const resetAllStores = () => {
  if (!store) {
    console.error('Pinia is not installed')
    return
  }
  const allStores = (store as any)._s
  for (const [_key, store] of allStores) {
    if (store.$id !== 'preferencesStore') {
      store.$reset()
    }
  }
}

export { resetAllStores, setupStore, store }
