sendGoogleAdIdentification static method

Future<Result> sendGoogleAdIdentification()

Implementation

static Future<Result<dynamic>> sendGoogleAdIdentification() async {
  final result = await checkKwikpassHealth();
  if(result.isSuccess) {
    final healthData = result.getDataOrThrow();
    if(healthData?.isKwikpassHealthy == false){
      throw Exception('Kwikpass is unhealthy');
    }
  }

  try {
    final gokwik = DioClient().getClient();

    // Get device info from cache
    final deviceInfoJson = await cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkDeviceInfo)!);
    final deviceInfoDetails = deviceInfoJson != null ? jsonDecode(deviceInfoJson) : <String, dynamic>{};

    // Get Ad ID (works for both Android and iOS)
    final adId = deviceInfoDetails[cdnConfigInstance.getKeys(StorageKeyKeys.gkGoogleAdId)!];

    // Get device ID
    final deviceId = deviceInfoDetails[cdnConfigInstance.getKeys(StorageKeyKeys.gkDeviceUniqueId)!];

    // Get merchant ID and request ID from cache
    final results = await Future.wait([
      cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkMerchantIdKey)!),
      cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkRequestIdKey)!),
    ]);

    final mid = results[0];
    final requestId = results[1];

    // Prepare headers
    final headers = <String, String>{
      cdnConfigInstance.getHeader(APIHeaderKeys.kpMerchantId)!: mid ?? '',
    };

    // Add request ID if available
    if (requestId != null && requestId.isNotEmpty) {
      headers[cdnConfigInstance.getHeader(APIHeaderKeys.kpRequestId)!] = requestId;
    }

    // Prepare query parameters with separate ad IDs for Android and iOS
    final params = <String, String>{};

    if (Platform.isAndroid && adId != null && adId.isNotEmpty) {
      params['google_ad_id'] = adId;
    }

    if (Platform.isIOS && adId != null && adId.isNotEmpty) {
      params['ios_ad_id'] = adId;
    }

    if (deviceId != null && deviceId.isNotEmpty) {
      params['deviceId'] = deviceId;
    }

    final response = await gokwik.get(
      cdnConfigInstance.getEndpoint(APIEndpointKeys.customerGoogleAd)!,
      queryParameters: params,
      options: Options(headers: headers),
    );

    return Success(response.data);
  } catch (err) {
    throw handleApiError(err);
  }
}