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

/// SQLite 本地键值缓存。
///
/// 约定：后端数据库是健康业务数据的唯一事实源。这里仅保存会话、偏好、
/// 草稿和临时缓存，不保存健康记录、报告、用药、饮食、AI 对话等核心业务事实。
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');
  }
}
