// Version: 1.1.0 | Created: 2026-04-01 | Updated: 2026-04-03
// Matrix SDK client singleton provider.
// The Matrix client is kept alive for the full app lifetime once initialised.

import 'package:matrix/matrix.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../config/app_config.dart';

part 'matrix_client.g.dart';

/// Provides the single [Client] instance used throughout the app.
///
/// keepAlive: true — the Matrix client must never be disposed while the app
/// is running; it holds the sync loop and all room state.
///
/// Uses [MatrixSdkDatabase] for event storage — without a database, the SDK
/// doesn't store timeline events and room.getTimeline() returns empty.
/// On web this uses IndexedDB via Hive; on mobile it uses SQLite.
@Riverpod(keepAlive: true)
Client matrixClient(Ref ref) {
  return Client(
    AppConfig.appName,
    databaseBuilder: (client) async {
      final db = MatrixSdkDatabase('m8chat_matrix');
      await db.open();
      return db;
    },
  );
}
