package io.layers.sdk.reactnative;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;

import java.util.concurrent.Executors;

/**
 * Native module for fetching the Google Advertising ID (GAID).
 *
 * Uses the Google Play Services AdvertisingIdClient API. This requires the
 * host app to include `com.google.android.gms:play-services-ads-identifier`
 * as a dependency. If the library is not present, the module resolves with null.
 */
public class LayersAdvertisingIdModule extends ReactContextBaseJavaModule {

    public LayersAdvertisingIdModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "LayersAdvertisingId";
    }

    @ReactMethod
    public void getAdvertisingInfo(Promise promise) {
        Executors.newSingleThreadExecutor().execute(() -> {
            try {
                // Use reflection to avoid hard dependency on play-services-ads-identifier
                Class<?> adIdClientClass = Class.forName(
                        "com.google.android.gms.ads.identifier.AdvertisingIdClient");
                java.lang.reflect.Method getInfoMethod = adIdClientClass.getMethod(
                        "getAdvertisingIdInfo", android.content.Context.class);
                Object adInfo = getInfoMethod.invoke(null, getReactApplicationContext());

                if (adInfo == null) {
                    promise.resolve(null);
                    return;
                }

                java.lang.reflect.Method getIdMethod = adInfo.getClass().getMethod("getId");
                java.lang.reflect.Method getLimitMethod = adInfo.getClass()
                        .getMethod("isLimitAdTrackingEnabled");

                String id = (String) getIdMethod.invoke(adInfo);
                boolean limitTracking = (Boolean) getLimitMethod.invoke(adInfo);

                if (id == null || id.equals("00000000-0000-0000-0000-000000000000")) {
                    promise.resolve(null);
                    return;
                }

                WritableMap result = Arguments.createMap();
                result.putString("id", id);
                result.putBoolean("isLimitAdTrackingEnabled", limitTracking);
                promise.resolve(result);
            } catch (ClassNotFoundException e) {
                // play-services-ads-identifier not available
                promise.resolve(null);
            } catch (Exception e) {
                promise.resolve(null);
            }
        });
    }
}
