import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

/// SQLite 本地数据库——存储 token 等关键信息
class LocalDatabase {
  static LocalDatabase? _instance;
  Database? _db;

  LocalDatabase._();

  static LocalDatabase get instance => _instance ??= LocalDatabase._();

  Future<Database> get database async {
    _db ??= await _initDb();
    return _db!;
  }

  Future<Database> _initDb() async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, 'health_app.db');
    return openDatabase(
      path,
      version: 1,
      onCreate: (db, version) async {
        await db.execute(
          'CREATE TABLE kv_store (key TEXT PRIMARY KEY, value TEXT)',
        );
      },
    );
  }

  Future<void> write(String key, String value) async {
    final db = await database;
    await db.insert(
      'kv_store',
      {'key': key, 'value': value},
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  Future<String?> read(String key) async {
    final db = await database;
    final result =
        await db.query('kv_store', where: 'key = ?', whereArgs: [key]);
    if (result.isEmpty) return null;
    return result.first['value'] as String?;
  }

  Future<void> delete(String key) async {
    final db = await database;
    await db.delete('kv_store', where: 'key = ?', whereArgs: [key]);
  }

  Future<void> deleteAll() async {
    final db = await database;
    await db.delete('kv_store');
  }
}
