import Dexie, { type Table } from 'dexie'
import type { GameData } from '@engine/types'

export interface VersionRecord {
  id?: number
  sourcePath: string
  timestamp: number
  label: string
  gameData: GameData
}

class EditorDB extends Dexie {
  versions!: Table<VersionRecord, number>

  constructor() {
    super('EditorVersions')
    this.version(1).stores({
      versions: '++id, sourcePath, timestamp',
    })
  }
}

const db = new EditorDB()

export async function putVersion(record: VersionRecord): Promise<void> {
  try {
    await db.versions.add(record)
    const all = await db.versions
      .where('sourcePath')
      .equals(record.sourcePath)
      .reverse()
      .sortBy('timestamp')
    if (all.length > 20) {
      const toDelete = all.slice(20)
      await db.versions.bulkDelete(toDelete.map((v) => v.id!))
    }
  } catch {}
}

export async function getVersions(sourcePath: string): Promise<VersionRecord[]> {
  try {
    return await db.versions
      .where('sourcePath')
      .equals(sourcePath)
      .reverse()
      .sortBy('timestamp')
  } catch {
    return []
  }
}

export async function clearVersions(sourcePath: string): Promise<void> {
  try {
    const records = await db.versions.where('sourcePath').equals(sourcePath).toArray()
    await db.versions.bulkDelete(records.map((v) => v.id!))
  } catch {}
}
