import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/user_info_bo.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);
  }

  Future<void> _onLoginRequested(
    AuthLoginRequested event,
    Emitter<AuthState> emit,
  ) async {
    emit(AuthLoading());
    
    try {
      // todo 这里暂定返回bool
      // final success = await _authService.login(event.username, event.password);
      final success = true;

      if (success) {
        final userInfo = const UserInfoBO(
          username: "张三丰",
        );
        emit(AuthSuccess(userInfo));
      } else {
        emit(const AuthFailure('登录失败，请检查用户名和密码'));
      }
    } catch (e) {
      emit(AuthFailure(e.toString()));
    }
  }

  Future<void> _onTokenExpired(
    AuthTokenExpiredEvent event,
    Emitter<AuthState> emit,
  ) async {
    await _storageService.deleteToken();
    emit(const AuthTokenExpired());
  }

  Future<void> _onLogoutRequested(
    AuthLogoutRequestedEvent event,
    Emitter<AuthState> emit,
  ) async {
    await _storageService.deleteToken();
    emit(const AuthLoggedOut());
  }
}
