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;
    bool disposeRequested = false;
    bool disposed = false;

    _pb
        .collection(collection)
        .subscribe(topic, onEvent, filter: filter)
        .then((fn) async {
      if (disposeRequested) {
        disposed = true;
        await fn();
        return;
      }
      cancel = fn;
    }).catchError((_) {});

    return () async {
      if (disposed) return;
      disposeRequested = true;
      try {
        final fn = cancel;
        if (fn != null) {
          disposed = true;
          await fn();
        }
      } catch (_) {
        // swallow — never globally unsubscribe the topic here, because
        // other screens may still be subscribed to the same collection/topic.
      }
    };
  }
}
