import localforage from 'localforage'
import { getProjectDbName } from '@/lib/workspace'

export const createProjectKvAdapter = (projectId: string) => {
  const projectKvForage = localforage.createInstance({
    name: getProjectDbName(projectId),
    storeName: 'pinia-kv'
  })
  return {
    setItem: async <T = unknown>(keyRaw: string | number, value: T) => {
      const key = String(keyRaw || '').trim()
      if (!key) return
      const currentState = await projectKvForage.getItem<Record<string, unknown>>('pinia-kv')
      const nextEntries = {
        ...(
          currentState?.entries && typeof currentState.entries === 'object'
            ? (currentState.entries as Record<string, unknown>)
            : {}
        ),
        [key]: JSON.parse(JSON.stringify(value))
      }
      await projectKvForage.setItem('pinia-kv', {
        ...(currentState && typeof currentState === 'object' ? currentState : {}),
        entries: nextEntries,
        ready: true
      })
    }
  }
}
