import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:storage_sdk/storage_sdk.dart';

import '../../data/local/drift/app_database.dart';

/// 全局单例 StorageSdkApi，整个 App 生命周期内唯一实例。
///
/// storage_sdk 负责数据库连接生命周期和 CRUD 机制；
/// im_app 负责 schema（AppDatabase + 各业务表）。
///
/// 用法：
/// ```dart
/// // 登录后开库
/// await ref.read(storageSdkLifecycleProvider).openDatabase(user.id);
///
/// // CRUD 示例
/// final db = ref.read(storageSdkProvider);
/// await db.insertOrReplace<UsersCompanion>(companion);
/// final users = await db.selectAll<User>();
/// ```

final storageSdkProvider = Provider<StorageSdkApi>((ref) {
  return StorageSdkApi(
    databaseFactory: (executor) => AppDatabase(executor),
    tableRegistry: (db) => AppDatabase.getTableRegistry(db),
  );
});

/// 生命周期管理，仅供登录/登出使用。
final storageSdkLifecycleProvider = Provider<StorageSdkLifecycle>((ref) {
  return ref.read(storageSdkProvider) as StorageSdkLifecycle;
});