import { db, type SettingsRecord } from './schema'
import { DEFAULT_SETTINGS, type Settings } from '../types/settings'
import { logError } from '../lib/errorHandler'

export const settingsRepository = {
  async load(): Promise<Settings> {
    try {
      const record: SettingsRecord | undefined = await db.settings.get('default')
      if (record) {
        return {
          darkMode: record.darkMode ?? DEFAULT_SETTINGS.darkMode,
          viewMode: record.viewMode ?? DEFAULT_SETTINGS.viewMode,
          sidebarCollapsed: record.sidebarCollapsed ?? DEFAULT_SETTINGS.sidebarCollapsed,
          sidebarWidth: record.sidebarWidth ?? DEFAULT_SETTINGS.sidebarWidth
        }
      }
    } catch (error) {
      logError('加载设置失败', error)
    }
    return { ...DEFAULT_SETTINGS }
  },

  // C-01: 先 load 再 merge 再 put，避免部分字段丢失
  // M-04: 添加错误处理与日志
  async save(partial: Partial<Settings>): Promise<void> {
    try {
      const current: Settings = await this.load()
      const merged: SettingsRecord = { id: 'default', ...current, ...partial }
      await db.settings.put(merged)
    } catch (error) {
      logError('保存设置失败', error)
    }
  }
}
