import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:meta/meta.dart';

part 'auth_state.dart';

class AuthCubit extends Cubit<AuthState> {
  AuthCubit() : super(AuthInitial());
  
  final Dio _dio = Dio(BaseOptions(
    connectTimeout: const Duration(seconds: 30),
    receiveTimeout: const Duration(seconds: 30),
  ));

  Future<void> sendOTP(String phoneNumber) async {
    emit(AuthLoading());
    try {
      final response = await _dio.post(
        'https://api-gateway.liara.run/auth/otp/generate',
        data: {'userId': phoneNumber},
      );
      print(response.toString());
      
      if (response.statusCode == 200 || response.statusCode == 201) {
        if (response.data['success'] == true) {
          emit(AuthSuccess(phoneNumber: phoneNumber));
          print(response.data.toString());
        } else {
          emit(AuthError('Failed to send OTP'));
        }
      } else {
        emit(AuthError('Server error: ${response.statusCode}'));
      }
    } on DioException catch (e) {
      emit(AuthError('Connection error: ${e.message}'));
    } catch (e) {
      emit(AuthError('Unexpected error occurred'));
    }
  }
}