package com.foxx.androidcast.commercial;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.google.android.play.core.review.ReviewInfo;
import com.google.android.play.core.review.ReviewManager;
import com.google.android.play.core.review.ReviewManagerFactory;

/**
 * Play Store listing and in-app review — active only when developer settings enable Play integration.
 */
public final class PlayStoreIntegration {
    private static final String TAG = "PlayStoreIntegration";
    private static volatile PlayStoreIntegration instance;

    private final Context appContext;
    private ReviewManager reviewManager;
    private boolean initialized;

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

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

    public void ensureInitialized() {
        if (!CommercialFeatures.isPlayStoreIntegrationEnabled(appContext)) {
            return;
        }
        if (initialized) {
            return;
        }
        reviewManager = ReviewManagerFactory.create(appContext);
        initialized = true;
        Log.i(TAG, "Play Store integration enabled (developer)");
    }

    public void openAppListing(Activity activity) {
        if (!CommercialFeatures.isPlayStoreIntegrationEnabled(appContext)) {
            return;
        }
        String pkg = appContext.getPackageName();
        try {
            activity.startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("market://details?id=" + pkg)));
        } catch (ActivityNotFoundException e) {
            activity.startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=" + pkg)));
        }
    }

    /** Launch Google Play in-app review flow when available (test via internal track). */
    public void requestInAppReviewIfAvailable(Activity activity) {
        if (!CommercialFeatures.isPlayStoreIntegrationEnabled(appContext) || reviewManager == null) {
            return;
        }
        reviewManager.requestReviewFlow().addOnCompleteListener(task -> {
            if (!task.isSuccessful()) {
                Log.w(TAG, "Review flow request failed");
                return;
            }
            ReviewInfo reviewInfo = task.getResult();
            reviewManager.launchReviewFlow(activity, reviewInfo);
        });
    }
}
