import 'package:flutter_bloc/flutter_bloc.dart';
import 'auth_event.dart';
import 'auth_state.dart';
import '../../services/auth_service.dart';
import '../../utils/storage/storage_service.dart';

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final AuthService _authService;
  final StorageService _storageService;

  AuthBloc({
    required AuthService authService,
    required StorageService storageService,
  })  : _authService = authService,
        _storageService = storageService,
        super(AuthInitial()) {
    on<AuthLoginRequested>(_onLoginRequested);
    on<AuthTokenExpiredEvent>(_onTokenExpired);
    on<AuthLogoutRequestedEvent>(_onLogoutRequested);
    on<AuthFetchUserInfo>(_onFetchUserInfo);
  }

  Future<void> _onLoginRequested(
    AuthLoginRequested event,
    Emitter<AuthState> emit,
  ) async {
    emit(AuthLoading());

    try {
      await _authService.login(event.username, event.password);

      // 登录成功后获取用户信息
      final userInfo = await _authService.getUserInfo();
      emit(AuthSuccess(userInfo));
    } catch (e) {
      emit(AuthFailure(e.toString()));
    }
  }

  Future<void> _onTokenExpired(
    AuthTokenExpiredEvent event,
    Emitter<AuthState> emit,
  ) async {
    // 防止重复处理：如果已经在过期或登出状态，直接跳过
    if (state is AuthTokenExpired || state is AuthLoggedOut) return;

    await _storageService.deleteToken();
    await _storageService.deleteUserInfo();
    await _storageService.deleteClientId();
    emit(const AuthTokenExpired());
  }

  Future<void> _onLogoutRequested(
    AuthLogoutRequestedEvent event,
    Emitter<AuthState> emit,
  ) async {
    try {
      await _authService.logout();
    } catch (_) {
      // 即使接口调用失败也继续执行本地登出
    }
    await _storageService.deleteToken();
    await _storageService.deleteUserInfo();
    await _storageService.deleteClientId();
    emit(const AuthLoggedOut());
  }

  Future<void> _onFetchUserInfo(
    AuthFetchUserInfo event,
    Emitter<AuthState> emit,
  ) async {
    try {
      final userInfo = await _authService.getUserInfo();
      emit(AuthSuccess(userInfo));
    } catch (e) {
      // 获取用户信息失败，尝试从本地读取
      final storedUserInfo = await _authService.getStoredUserInfo();
      if (storedUserInfo != null) {
        emit(AuthSuccess(storedUserInfo));
      }
    }
  }
}