import { ref, readonly } from 'vue'
import { db } from '../db/database.js'

const initialized = ref(false)
const initializing = ref(false)
const dbInfo = ref(null)
const error = ref(null)
const migrationPending = ref(null)

export function useDatabase() {
  async function init() {
    if (initialized.value || initializing.value) return dbInfo.value
    initializing.value = true
    try {
      dbInfo.value = await db.init()
      migrationPending.value = db.migrationPending
      initialized.value = !db.migrationPending
      return dbInfo.value
    } catch (e) {
      error.value = e.message
      throw e
    } finally {
      initializing.value = false
    }
  }

  async function runPendingMigrations() {
    await db.runPendingMigrations()
    migrationPending.value = null
    initialized.value = true
  }

  return {
    initialized: readonly(initialized),
    initializing: readonly(initializing),
    dbInfo: readonly(dbInfo),
    error: readonly(error),
    migrationPending: readonly(migrationPending),
    init,
    runPendingMigrations,
  }
}
