registerPushToken method

Future<void> registerPushToken(
  1. DeviceType type,
  2. String token
)

Implementation

Future<void> registerPushToken(DeviceType type, String token) async {
  final storage = HiveStorageService.instance;

  final deviceId = await storage.getDeviceId();
  if (deviceId == null) {
    throw Exception(
      'Please provide deviceId using client.setDeviceId() before using the client!',
    );
  }

  Map<String, dynamic> request = Map<String, dynamic>.from({
    'profileId': await storage.getProfileId(),
    'deviceType': type.name,
    'deviceId': deviceId,
    'pushToken': token,
  });

  try {
    final response = await http.post(
      Uri.parse('${_getEndpoint()}/api/v0/appPush/tokens'),
      headers: {
        'content-type': 'application/json',
        'authorization': 'Bearer $_accessToken',
      },
      body: jsonEncode(request),
    );

    if (response.statusCode != 202) {
      throw Exception(
        'Backend API error: ${response.statusCode} - ${response.body}',
      );
    }

    _cartChanged = false;
    _wishlistChanged = false;
    _profileChanged = false;
    _deviceIdChanged = false;
    // Note: We don't clear merge profile IDs here because this endpoint
    // doesn't send merge data. Merge IDs are only cleared in push() after
    // they've been successfully sent to the API.
  } catch (e) {
    rethrow;
  }
}