import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/// 认证事件类型
enum AuthEventType {
  /// Token 过期，需要重新登录
  tokenExpired,
}

/// 认证事件
class AuthEvent {
  final AuthEventType type;
  final String? message;

  AuthEvent({
    required this.type,
    this.message,
  });
}

/// 认证事件服务
///
/// 用于在 token 过期等情况下通知 UI 层进行页面跳转
class AuthEventService {
  /// 单例实例
  static final AuthEventService _instance = AuthEventService._internal();

  factory AuthEventService() => _instance;

  AuthEventService._internal();

  /// 事件流控制器
  final _eventController = StreamController<AuthEvent>.broadcast();

  /// 获取事件流
  Stream<AuthEvent> get events => _eventController.stream;

  /// 全局 Navigator Key（由 AppRouter 设置）
  GlobalKey<NavigatorState>? navigatorKey;

  /// 发送 token 过期事件
  void emitTokenExpired({String? message}) {
    debugPrint('[AuthEventService] Emitting token expired event');
    _eventController.add(AuthEvent(
      type: AuthEventType.tokenExpired,
      message: message ?? '登录已过期，请重新登录',
    ));
  }

  /// 释放资源
  void dispose() {
    _eventController.close();
  }
}

/// 认证事件服务 Provider
final authEventServiceProvider = Provider<AuthEventService>((ref) {
  return AuthEventService();
});
