import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'auth_bridge.g.dart';

/// Shared mutable auth state: decouples api_client / WS notifiers
/// (read-only consumers) from auth_notifier (writer). Also de-dupes
/// concurrent 401-triggered refreshes.
///
/// Auth notifier calls [setAccessToken] on successful auth / refresh,
/// registers [refresh] and [onUnauthenticated] callbacks on build.
class AuthBridge {
  String? accessToken;
  Future<String?> Function()? refresh;
  void Function()? onUnauthenticated;

  Completer<String?>? _inFlight;

  void setAccessToken(String? token) {
    accessToken = token;
  }

  void clear() {
    accessToken = null;
  }

  Future<String?> tryRefresh() {
    final existing = _inFlight;
    if (existing != null) return existing.future;
    final completer = Completer<String?>();
    _inFlight = completer;
    () async {
      try {
        final next = await refresh?.call();
        completer.complete(next);
      } catch (_) {
        completer.complete(null);
      } finally {
        _inFlight = null;
      }
    }();
    return completer.future;
  }

  void notifyUnauthenticated() {
    onUnauthenticated?.call();
  }
}

@Riverpod(keepAlive: true)
AuthBridge authBridge(Ref ref) => AuthBridge();
