import 'package:flutter_bloc/flutter_bloc.dart';
import '../../domain/usecases/send_otp.dart';
import '../../domain/usecases/verify_otp.dart';

part 'auth_event.dart';
part 'auth_state.dart';

class AuthBloc extends Bloc<AuthEvent, AuthState> {
  final SendOTP sendOTPUseCase;
  final VerifyOTP verifyOTPUseCase;

  String _timeStamp = "";
  String _timeDue = "";

  String get timeStamp => _timeStamp;
  String get timeDue => _timeDue;

  AuthBloc({
    required this.sendOTPUseCase,
    required this.verifyOTPUseCase,
  }) : super(AuthInitial()) {
    on<SendOTPEvent>(_onSendOTP);
    on<VerifyOTPEvent>(_onVerifyOTP);
  }

  Future<void> _onSendOTP(SendOTPEvent event, Emitter<AuthState> emit) async {
    emit(AuthLoading());

    final result = await sendOTPUseCase(SendOTPParams(phoneNumber: event.phoneNumber));

    if (result.isSuccess && result.data != null) {
      _timeStamp = result.data!.timeStamp;
      _timeDue = result.data!.timeDue;
      emit(AuthSuccess(
        phoneNumber: event.phoneNumber,
        timeStamp: _timeStamp,
        timeDue: _timeDue,
      ));
    } else {
      emit(AuthError('خطا در ارسال کد. لطفاً دوباره تلاش کنید.'));
    }
  }

  Future<void> _onVerifyOTP(VerifyOTPEvent event, Emitter<AuthState> emit) async {
    emit(AuthLoading());

    final result = await verifyOTPUseCase(VerifyOTPParams(
      otpCode: event.otpCode,
      phoneNumber: event.phoneNumber,
    ));

    if (result.isSuccess && result.data == true) {
      emit(OTPVerified());
    } else {
      emit(AuthError('کد وارد شده نادرست است. لطفاً دوباره تلاش کنید.'));
    }
  }
}
