import 'package:flutter/foundation.dart' show debugPrint;

import 'mattermost_auth_service.dart';
import 'mattermost_push_client.dart';

/// Owns the Mattermost host/plugin responsibility boundary.
///
/// The integration:
///   - initializes the push client exactly once,
///   - performs auto-login best-effort (skips silently when credentials are
///     unavailable, so app boot is not blocked),
///   - registers navigation callbacks in one place (not from a widget build),
///   - exposes the notification stream for app-level consumers.
class MattermostPushHostIntegration {
  final MattermostPushClient pushClient;
  final MattermostAuthService Function(MattermostPushClient client)
  _authServiceFactory;

  bool _initialized = false;

  MattermostPushHostIntegration({
    required this.pushClient,
    MattermostAuthService Function(MattermostPushClient client)?
    authServiceFactory,
  }) : _authServiceFactory =
           authServiceFactory ??
           ((MattermostPushClient client) => MattermostAuthService(client));

  Stream<Map<String, dynamic>> get onNotification => pushClient.onNotification;

  bool get isInitialized => _initialized;

  /// Initialize plugin, perform auth handoff, and register navigation
  /// callbacks. Safe to call once at bootstrap; subsequent calls are no-ops.
  ///
  /// [onNavigateToChannel] / [onNavigateToThread] are optional. When omitted,
  /// the integration installs debug-logging fallbacks so the navigation path
  /// remains observable without forcing the caller to wire routing.
  Future<void> initialize({
    void Function(String serverUrl, String channelId)? onNavigateToChannel,
    void Function(String serverUrl, String rootId)? onNavigateToThread,
  }) async {
    if (_initialized) return;
    _initialized = true;

    await pushClient.initialize();

    final authService = _authServiceFactory(pushClient);
    try {
      await authService.autoLoginAndRegister();
    } catch (e) {
      debugPrint('[MattermostHost] Mattermost auto-login failed: $e');
    }

    pushClient.onNavigateToChannel =
        onNavigateToChannel ??
        (serverUrl, channelId) {
          debugPrint(
            '[MattermostHost] Navigate to channel: $channelId on $serverUrl',
          );
        };
    pushClient.onNavigateToThread =
        onNavigateToThread ??
        (serverUrl, rootId) {
          debugPrint(
            '[MattermostHost] Navigate to thread: $rootId on $serverUrl',
          );
        };
  }
}
