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

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

  AuthBloc({required this.authRepository}) : super(const AuthState.initial()) {
    on<AuthEventStarted>(_onStarted);
    on<AuthEventLoginRequested>(_onLoginRequested);
    on<AuthEventRegisterRequested>(_onRegisterRequested);
    on<AuthEventLogoutRequested>(_onLogoutRequested);
    on<AuthEventAuthChecked>(_onAuthChecked);
    on<AuthEventUsernameChanged>(_onUsernameChanged);
    on<AuthEventPasswordChanged>(_onPasswordChanged);
    on<AuthEventNameChanged>(_onNameChanged);
  }

  Future<void> _onStarted(AuthEventStarted event, Emitter<AuthState> emit) async {
    add(const AuthEvent.authChecked());
  }

  Future<void> _onLoginRequested(AuthEventLoginRequested event, Emitter<AuthState> emit) async {
    emit(const AuthState.loading());
    final result = await authRepository.login(event.username, event.password);
    result.fold(
      (error) => emit(AuthState.error('loginFailed')),
      (user) => emit(AuthState.authenticated(user.id)),
    );
  }

  Future<void> _onRegisterRequested(AuthEventRegisterRequested event, Emitter<AuthState> emit) async {
    emit(const AuthState.loading());
    final result = await authRepository.register(event.username, event.password, event.name);
    result.fold(
      (error) => emit(AuthState.error('registrationFailed')),
      (user) => emit(AuthState.authenticated(user.id)),
    );
  }

  Future<void> _onLogoutRequested(AuthEventLogoutRequested event, Emitter<AuthState> emit) async {
    emit(const AuthState.loading());
    await authRepository.logout();
    emit(const AuthState.unauthenticated());
  }

  Future<void> _onAuthChecked(AuthEventAuthChecked event, Emitter<AuthState> emit) async {
    final result = await authRepository.getCurrentUser();
    result.fold(
      (error) => emit(const AuthState.unauthenticated()),
      (user) => emit(AuthState.authenticated(user.id)),
    );
  }

  void _onUsernameChanged(AuthEventUsernameChanged event, Emitter<AuthState> emit) {}
  void _onPasswordChanged(AuthEventPasswordChanged event, Emitter<AuthState> emit) {}
  void _onNameChanged(AuthEventNameChanged event, Emitter<AuthState> emit) {}
}
