package com.tencent.qian.webview.internal;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.tencent.qian.webview.model.SignCallback;
import com.tencent.qian.webview.model.SignResult;
import com.tencent.qian.webview.model.TencentQianWebViewConfig;

/**
 * 进程内全局回调桥（Phase 1 简单实现：单 slot，容器模式同时只允许 1 个签署窗口）。
 */
public final class IntentBridge {

    private static final String TAG = "QianIntentBridge";

    @Nullable
    private static volatile SignCallback pendingCallback;

    @Nullable
    private static volatile TencentQianWebViewConfig pendingConfig;

    private IntentBridge() {}

    public static void put(@Nullable SignCallback callback, @NonNull TencentQianWebViewConfig config) {
        // 竞态保护：旧 callback 未消费时，先派发空结果释放调用方
        SignCallback prev = pendingCallback;
        if (prev != null) {
            Log.w(TAG, "put() called while previous callback is still pending. " +
                    "Dispatching empty result to previous callback to prevent leak.");
            try {
                prev.onSignResult(SignResult.EMPTY);
            } catch (Exception e) {
                Log.w(TAG, "Error dispatching empty result to previous callback", e);
            }
        }
        pendingCallback = callback;
        pendingConfig = config;
    }

    @Nullable
    public static SignCallback takeCallback() {
        SignCallback cb = pendingCallback;
        pendingCallback = null;
        return cb;
    }

    @NonNull
    public static TencentQianWebViewConfig takeConfig() {
        TencentQianWebViewConfig cfg = pendingConfig;
        pendingConfig = null;
        return cfg != null ? cfg : TencentQianWebViewConfig.DEFAULT;
    }

    public static void clear() {
        pendingCallback = null;
        pendingConfig = null;
    }

    public static boolean hasPending() {
        return pendingCallback != null;
    }
}
