import 'package:dio/dio.dart'; import 'package:kmobile/data/models/ifsc.dart'; import 'package:kmobile/data/models/beneficiary.dart'; class BeneficiaryService { final Dio _dio; BeneficiaryService(this._dio); Future validateBeneficiaryWithinBank(String accountNumber) async { try { final response = await _dio.get('/api/beneficiary/validate/within-bank', queryParameters: { 'accountNumber': accountNumber, }); if (response.statusCode == 200) { return response.data['name']; } else { throw Exception(response.data['error'] ?? 'Failed to validate beneficiary'); } } on DioException catch (e) { throw Exception('Network error: ${e.message}'); } catch (e) { throw Exception('Unexpected error: ${e.toString()}'); } } Future validateIFSC(String ifscCode) async { try { final response = await _dio.get('/api/beneficiary/ifsc-details', queryParameters: { "ifscCode": ifscCode } ); if (response.statusCode == 200) { return ifsc.fromJson(response.data); } } on DioException catch (e) { if (e.response?.statusCode == 404) { print('Invalid IFSC code.'); } else { print('API error: ${e.message}'); } } catch (e) { print('Unexpected error: $e'); } return null; } // Send Data for Validation Future sendForValidation(Beneficiary beneficiary) async { try { print(beneficiary.toJson()); final response = await _dio.post( '/api/beneficiary/add', data: beneficiary.toJson(), ); if (response.statusCode == 200) { print("SENT FOR VALIDATION"); } else { print("VALIDATION REQUEST FAILED: ${response.statusCode}"); } } catch (e) { print("ERROR IN SENDING REQUEST: $e"); rethrow; } } // Poll to check if beneficiary is found Future checkIfFound(String accountNo) async { const int timeoutInSeconds = 30; const int intervalInSeconds = 2; const int maxTries = timeoutInSeconds ~/ intervalInSeconds; int attempts = 0; while (attempts < maxTries) { try { final response = await _dio.get( '/api/beneficiary/check?', queryParameters: { 'accountNo': accountNo } ); if (response.statusCode == 200) { print("FOUND"); return true; } else if (response.statusCode == 404) { print("NOT FOUND"); } } catch (e) { print("ERROR DURING STATUS: $e"); } attempts++; } print("Beneficiary not found within timeout."); return false; } }