// ============================================================
// infrastructure/storage/settings-store.ts — 应用设置持久化
//
// 职责：
//   - 读写 key-value 格式的应用设置（如 outputPath）
//   - 提供同步读取方法（无 async overhead）
//   - 兼容现有的 localStorage 设置逻辑
// ============================================================

import { execute, queryAll, queryOne } from '../core/db-core';
import type { AppSetting } from '../core/types';
import { SETTING_KEYS } from '../core/types';

// ---------- API ----------

export function setSetting(key: string, value: string): void {
  execute(
    `INSERT OR REPLACE INTO app_settings (key, value, updated_at) VALUES (?, ?, ?)`,
    [key, value, Date.now()],
  );
}

export function getSetting(key: string): string | null {
  const row = queryOne<AppSetting>(`SELECT value FROM app_settings WHERE key = ?`, [key]);
  return row?.value ?? null;
}

export function getAllSettings(): AppSetting[] {
  return queryAll<AppSetting>(`SELECT * FROM app_settings ORDER BY key`);
}

export function deleteSetting(key: string): void {
  execute(`DELETE FROM app_settings WHERE key = ?`, [key]);
}

// ---------- 便捷方法（兼容 SettingsProvider） ----------

export function getOutputPath(): string {
  return getSetting(SETTING_KEYS.OUTPUT_PATH) || '';
}

export function setOutputPath(path: string): void {
  setSetting(SETTING_KEYS.OUTPUT_PATH, path);
}

export function getTeamRepoPath(): string {
  return getSetting(SETTING_KEYS.TEAM_REPO_PATH) || '';
}

export function setTeamRepoPath(path: string): void {
  setSetting(SETTING_KEYS.TEAM_REPO_PATH, path);
}
