package com.foxx.androidcast.commercial;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.PendingPurchasesParams;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.QueryProductDetailsParams;
import java.util.Collections;
import java.util.List;

/**
 * Google Play Billing wrapper — connects only when developer settings enable IAP.
 * Product IDs are placeholders until Play Console SKUs exist.
 */
public final class InAppPurchaseCoordinator implements PurchasesUpdatedListener {
    private static final String TAG = "InAppPurchaseCoordinator";

    /** Example SKU — create matching in-app product in Play Console before release. */
    public static final String SKU_PREMIUM = "androidcast_premium";

    private static volatile InAppPurchaseCoordinator instance;

    private final Context appContext;
    private BillingClient billingClient;
    private boolean initialized;

    public static InAppPurchaseCoordinator getInstance(Context context) {
        if (instance == null) {
            synchronized (InAppPurchaseCoordinator.class) {
                if (instance == null) {
                    instance = new InAppPurchaseCoordinator(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    private InAppPurchaseCoordinator(Context appContext) {
        this.appContext = appContext;
    }

    public void ensureInitialized() {
        if (!CommercialFeatures.isInAppPurchaseEnabled(appContext)) {
            return;
        }
        if (initialized && billingClient != null) {
            return;
        }
        billingClient = BillingClient.newBuilder(appContext)
                .setListener(this)
                .enablePendingPurchases(PendingPurchasesParams.newBuilder().enableOneTimeProducts().build())
                .build();
        billingClient.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(BillingResult billingResult) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    initialized = true;
                    Log.i(TAG, "Billing connected (developer IAP enabled)");
                } else {
                    Log.w(TAG, "Billing setup: " + billingResult.getDebugMessage());
                }
            }

            @Override
            public void onBillingServiceDisconnected() {
                initialized = false;
            }
        });
    }

    public void shutdown() {
        if (billingClient != null) {
            billingClient.endConnection();
            billingClient = null;
        }
        initialized = false;
    }

    public boolean isReady() {
        return initialized && billingClient != null && billingClient.isReady();
    }

    /** Query placeholder SKU for developer testing (no UI yet). */
    public void queryPremiumProduct(Runnable onDone) {
        if (!isReady()) {
            if (onDone != null) {
                onDone.run();
            }
            return;
        }
        QueryProductDetailsParams.Product product = QueryProductDetailsParams.Product.newBuilder()
                .setProductId(SKU_PREMIUM)
                .setProductType(BillingClient.ProductType.INAPP)
                .build();
        QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder()
                .setProductList(Collections.singletonList(product))
                .build();
        billingClient.queryProductDetailsAsync(params, (billingResult, productDetailsList) -> {
            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK
                    && productDetailsList != null && !productDetailsList.isEmpty()) {
                Log.i(TAG, "Product available: " + SKU_PREMIUM);
            } else {
                Log.w(TAG, "Product query: " + billingResult.getDebugMessage());
            }
            if (onDone != null) {
                onDone.run();
            }
        });
    }

    @Override
    public void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) {
        if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK || purchases == null) {
            return;
        }
        for (Purchase purchase : purchases) {
            Log.i(TAG, "Purchase state: " + purchase.getPurchaseState() + " products=" + purchase.getProducts());
        }
    }
}
