import '../../../core/database/database_service.dart';

/// 设置服务
/// 管理系统设置（密码、语言偏好等）
class SettingsService {
  static final SettingsService instance = SettingsService._internal();
  final DatabaseService _db = DatabaseService.instance;

  SettingsService._internal();

  /// 获取密码
  Future<String> getPassword() async {
    final database = await _db.database;
    final results = await database.query(
      'settings',
      where: 'key = ?',
      whereArgs: ['password'],
    );
    if (results.isEmpty) return '123456'; // 默认密码
    return results.first['value'] as String;
  }

  /// 设置密码
  Future<bool> setPassword(String newPassword) async {
    final database = await _db.database;
    final count = await database.update(
      'settings',
      {'value': newPassword},
      where: 'key = ?',
      whereArgs: ['password'],
    );
    return count > 0;
  }

  /// 验证密码
  Future<bool> verifyPassword(String password) async {
    final storedPassword = await getPassword();
    return password == storedPassword;
  }

  /// 获取设置值
  Future<String?> getSetting(String key) async {
    final database = await _db.database;
    final results = await database.query(
      'settings',
      where: 'key = ?',
      whereArgs: [key],
    );
    if (results.isEmpty) return null;
    return results.first['value'] as String;
  }

  /// 设置值
  Future<bool> setSetting(String key, String value) async {
    final database = await _db.database;
    // 使用 insert 或 replace
    await database.execute(
      'INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)',
      [key, value],
    );
    return true;
  }
}