import 'package:pocketbase/pocketbase.dart';
import '../api/pocketbase_client.dart';

typedef UnsubFn = Future<void> Function();

class RealtimeService {
  RealtimeService._();
  static final instance = RealtimeService._();

  final _pb = PocketBaseClient.instance.pb;

  UnsubFn watch(
    String collection, {
    String topic = '*',
    String filter = '',
    required void Function(RecordSubscriptionEvent) onEvent,
  }) {
    UnsubFn? cancel;

    _pb.collection(collection).subscribe(topic, onEvent, filter: filter).then((fn) {
      cancel = fn;
    });

    return () async {
      try {
        final fn = cancel;
        if (fn != null) {
          await fn();
        } else {
          await _pb.collection(collection).unsubscribe(topic);
        }
      } catch (_) {
        await _pb.collection(collection).unsubscribe(topic);
      }
    };
  }
}
