import Dexie from 'dexie'

class BookmarkDatabase extends Dexie {
  links
  settings

  constructor() {
    super('bookmark_index')

    this.version(1).stores({
      links: 'id, createdAt, updatedAt, title, *tags, *projectIds, visitCount, lastVisitTime',
      settings: 'id',
    })

    // 版本2：添加order字段用于拖拽排序
    this.version(2).stores({
      links: 'id, order, createdAt, updatedAt, title, *tags, *projectIds, visitCount, lastVisitTime',
      settings: 'id',
    }).upgrade(tx => {
      // 为现有记录设置默认排序值
      return tx.table('links').toCollection().modify(link => {
        if (link.order === undefined) {
          const createdTime = link.createdAt ? new Date(link.createdAt).getTime() : Date.now()
          link.order = createdTime
        }
      })
    })

    this.links = this.table('links')
    this.settings = this.table('settings')
  }
}

export const db = new BookmarkDatabase()

