login method

Future<void> login({
  1. required String email,
  2. required String password,
})

Authenticates the user with email and password.

On success, stores the token via Fresh and emits AuthenticationStatus.authenticated on statusChanges.

Throws FormatException if the server response cannot be parsed. Throws DioException on network or server errors.

Implementation

Future<void> login({required String email, required String password}) async {
  // TODO: swap getDummyLogin() → login(email: email, password: password) when API is ready
  final Response<dynamic> response = await _authService.getDummyLogin();

  final dynamic raw = response.data;
  final Map<String, dynamic>? json = (raw is Map<String, dynamic>)
      ? raw
      : (raw is Map && raw['data'] is Map<String, dynamic>)
      ? raw['data'] as Map<String, dynamic>
      : null;

  if (json == null) {
    final String preview = raw.toString();
    _logger.warn(
      '[AuthRepository] Login response has unexpected format',
      extras: <String, Object?>{
        'response.runtimeType': raw.runtimeType.toString(),
        'response.preview': preview.substring(0, preview.length.clamp(0, 200)),
      },
    );
    throw const FormatException('Unexpected login response format');
  }

  final AuthTokenModel? token = AuthTokenModel.tryFromJson(json, convert: true);

  if (token == null || token.isEmpty) {
    _logger.warn('[AuthRepository] Failed to parse token from login response');
    throw const FormatException('Failed to parse auth token');
  }

  await _fresh.setToken(token);
  _logger.info('[AuthRepository] Login successful — token stored');
  _emitStatus(AuthenticationStatus.authenticated);
}