import 'package:dio/dio.dart'; import '../../../../core/network/dio_client.dart'; import '../../../../core/security/crypto_service.dart'; class AuthRepository { final Dio dio = DioClient().dio; final CryptoService _crypto = CryptoService(); Future _ensureCryptoReady() async { if (!_crypto.isInitialized) { await _crypto.fetchPublicKey(); } } Future signup(String email, String password) async { try { await _ensureCryptoReady(); await dio.post( '/auth/signup', data: { 'email': _crypto.encrypt(email), 'password': _crypto.encrypt(password), }, ); } on DioException catch (e) { final data = e.response?.data; final errorMsg = data is Map ? data['error'] : data; throw Exception(errorMsg ?? e.message); } } Future> login(String email, String password) async { try { return await _attemptLogin(email, password); } on DioException catch (e) { if (e.response?.statusCode == 500 || e.response?.statusCode == 400 || e.response?.statusCode == 401) { _crypto.clearKey(); try { return await _attemptLogin(email, password); } on DioException catch (e2) { final data = e2.response?.data; final errorMsg = data is Map ? data['error'] : data; throw Exception(errorMsg ?? 'Invalid email or password'); } } final data = e.response?.data; final errorMsg = data is Map ? data['error'] : data; throw Exception(errorMsg ?? 'Invalid email or password'); } } Future> _attemptLogin( String email, String password, ) async { await _ensureCryptoReady(); final response = await dio.post( '/auth/login', data: { 'email': _crypto.encrypt(email), 'password': _crypto.encrypt(password), }, ); return response.data; } Future> verifyOtp(String email, String otp) async { try { final response = await dio.post( '/auth/verify-otp', data: {'email': email, 'otp': otp}, ); return response.data; } on DioException catch (e) { final data = e.response?.data; final errorMsg = data is Map ? data['error'] : data; throw Exception(errorMsg ?? 'Invalid OTP'); } } Future forgotPassword(String email) async { try { await dio.post('/auth/forgot-password', data: {'email': email}); } on DioException catch (e) { final data = e.response?.data; final errorMsg = data is Map ? data['error'] : data; throw Exception(errorMsg ?? 'Failed to send reset code'); } } Future resetPassword( String email, String otp, String newPassword, ) async { try { await _ensureCryptoReady(); await dio.post( '/auth/reset-password', data: { 'email': email, 'otp': otp, 'newPassword': _crypto.encrypt(newPassword), }, ); } on DioException catch (e) { final data = e.response?.data; final errorMsg = data is Map ? data['error'] : data; throw Exception(errorMsg ?? 'Failed to reset password'); } } }