import Dexie, { type EntityTable } from 'dexie'

export interface TabSnapshot {
  id: string
  filePath: string | null
  content: string
  scrollTop: number
  selectionStart: number
  selectionEnd: number
  isModified: boolean
  updatedAt: number
}

export interface ActiveTabRecord {
  id: string // 固定为 'current'
  activeTabId: string | null
}

export interface SettingsRecord {
  id: string // 固定为 'default'
  darkMode: boolean
  viewMode: 'editor' | 'preview' | 'source'
  sidebarCollapsed: boolean
  sidebarWidth: number
}

export interface RecentFile {
  id?: number
  filePath: string
  lastOpened: number
}

const db = new Dexie('MarkLite') as Dexie & {
  tabSnapshots: EntityTable<TabSnapshot, 'id'>
  settings: EntityTable<SettingsRecord, 'id'>
  recentFiles: EntityTable<RecentFile, 'id'>
  activeTab: EntityTable<ActiveTabRecord, 'id'>
}

db.version(1).stores({
  tabSnapshots: 'id, filePath, updatedAt',
  settings: 'id',
  recentFiles: '++id, filePath, lastOpened',
  activeTab: 'id'
})

export { db }
