import { db, type TabSnapshot } from './schema'
import { logError } from '../lib/errorHandler'

export const tabRepository = {
  async saveAll(tabs: TabSnapshot[]): Promise<void> {
    try {
      await db.transaction('rw', db.tabSnapshots, async () => {
        await db.tabSnapshots.clear()
        await db.tabSnapshots.bulkAdd(tabs)
      })
    } catch (error) {
      logError('保存标签快照失败', error)
    }
  },

  async loadAll(): Promise<TabSnapshot[]> {
    try {
      return await db.tabSnapshots.orderBy('updatedAt').toArray()
    } catch (error) {
      logError('加载标签快照失败', error)
      return []
    }
  },

  async clearAll(): Promise<void> {
    try {
      await db.tabSnapshots.clear()
    } catch (error) {
      logError('清空标签快照失败', error)
    }
  },

  async saveActiveTabId(tabId: string | null): Promise<void> {
    try {
      await db.activeTab.put({ id: 'current', activeTabId: tabId })
    } catch (error) {
      logError('保存活动标签ID失败', error)
    }
  },

  async loadActiveTabId(): Promise<string | null> {
    try {
      const record = await db.activeTab.get('current')
      return record?.activeTabId ?? null
    } catch (error) {
      logError('加载活动标签ID失败', error)
      return null
    }
  }
}
