getCustomer function

Implementation

Future<ApacuanaSuccess<GetCustomerData>> getCustomer() async {
  final cfg = getConfig();

  if (cfg.verificationId.isEmpty || cfg.customerId.isEmpty) {
    throw ApacuanaAPIError(
      "Both 'verificationId' and 'customerId' must be configured.",
      statusCode: 400,
      errorCode: 'CONFIGURATION_ERROR',
    );
  }

  final body = <String, dynamic>{
    'verificationid': cfg.verificationId,
    'customerid': cfg.customerId,
  };

  try {
    final res = await httpRequest(
      '/services/api/register/init',
      data: body,
      method: 'POST',
    );

    if (res is! Map) {
      throw ApacuanaAPIError(
        'The API response does not contain the user.',
        statusCode: 200,
        errorCode: 'INVALID_API_RESPONSE',
      );
    }

    final map = res.cast<String, dynamic>();
    final token = (map['sessionid'] ?? '').toString();
    final entry = (map['entry'] is Map)
        ? (map['entry'] as Map).cast<String, dynamic>()
        : <String, dynamic>{};

    if (token.isEmpty || entry.isEmpty) {
      throw ApacuanaAPIError(
        'The API response does not contain the user.',
        statusCode: 200,
        errorCode: 'INVALID_API_RESPONSE',
      );
    }

    return ApacuanaSuccess<GetCustomerData>(
      GetCustomerData(token: token, userData: entry),
    );
  } catch (e) {
    if (e is ApacuanaAPIError) {
      rethrow;
    }
    throw ApacuanaAPIError(
      'Unexpected failure getting token: ${e is Exception ? e.toString() : 'Unknown error'}',
    );
  }
}