import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/auth_repository.dart';
import 'auth_event.dart';
import 'auth_state.dart';

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final AuthRepository _repository;

  AuthBloc(this._repository) : super(AuthInitial()) {
    on<AuthStarted>(_onStarted);
    on<AuthLoggedIn>(_onLoggedIn);
    on<AuthLoggedOut>(_onLoggedOut);
  }

  Future<void> _onStarted(AuthStarted event, Emitter<AuthState> emit) async {
    emit(AuthLoading());
    final refreshToken = await _repository.getRefreshToken();
    if (refreshToken != null) {
      try {
        final response = await _repository.refreshSession(refreshToken);
        emit(
          AuthAuthenticated(
            user: AuthUser(id: response.user.id, email: response.user.email),
          ),
        );
        return;
      } catch (_) {
        await _repository.deleteSession();
      }
    }
    emit(AuthUnauthenticated());
  }

  void _onLoggedIn(AuthLoggedIn event, Emitter<AuthState> emit) {
    emit(AuthAuthenticated(user: event.user));
  }

  Future<void> _onLoggedOut(
    AuthLoggedOut event,
    Emitter<AuthState> emit,
  ) async {
    await _repository.deleteSession();
    emit(AuthUnauthenticated());
  }
}
