import '../../core/network/api_client.dart';
import '../../core/storage/token_storage.dart';

/// دسترسی به endpointهای احراز هویت (login-otp / check-otp).
class AuthRepository {
  final ApiClient _api;
  final TokenStorage _storage;

  AuthRepository(this._api, this._storage);

  /// درخواست ارسال کد یک‌بارمصرف.
  Future<void> requestOtp(String mobile) async {
    await _api.dio.post('/auth/login-otp', data: {'mobile': mobile});
  }

  /// اعتبارسنجی کد و ذخیره‌ی توکن JWT.
  Future<void> verifyOtp(String mobile, String code) async {
    final res = await _api.dio.post(
      '/auth/check-otp',
      data: {'mobile': mobile, 'token': code},
    );
    final token = res.data['token'] as String?;
    if (token == null || token.isEmpty) {
      throw Exception('no token in response');
    }
    await _storage.write(token);
  }

  Future<bool> isLoggedIn() async {
    final t = await _storage.read();
    return t != null && t.isNotEmpty;
  }

  Future<void> logout() => _storage.clear();
}
