/**
 * Request WeChat Mini Program Subscription Message
 * Template ID: iG5GYMPQAgKxIE9zZNOgKS6tCURhM9p9AC8iZ3Uj3uA
 */
const DEFAULT_TEMPLATE_ID = 'iG5GYMPQAgKxIE9zZNOgKS6tCURhM9p9AC8iZ3Uj3uA';
const MIN_SUB_INTERVAL = 5000; // Minimum 5 seconds between real requests
let lastSubTime = 0;

export const requestSubscription = (tmplIds = [DEFAULT_TEMPLATE_ID], silent = false) => {
    return new Promise((resolve) => {
        const now = Date.now();

        // Throttling for silent requests to avoid "frequent request" errors
        if (silent && (now - lastSubTime < MIN_SUB_INTERVAL)) {
            console.log('[Subscribe] Throttled: Skipping real request to avoid frequency errors');
            resolve({ success: true, throttled: true });
            return;
        }

        if (!wx.requestSubscribeMessage) {
            if (!silent) console.warn('当前版本不支持订阅消息');
            resolve({ success: false, errMsg: 'Not supported' });
            return;
        }

        // Update lastSubTime before the call
        lastSubTime = now;

        wx.requestSubscribeMessage({
            tmplIds: tmplIds,
            success(res) {
                // Log detailed results for debugging
                console.log('[Subscribe] Result:', res);

                // Check if any requested IDs were accepted
                const acceptedIds = tmplIds.filter(id => res[id] === 'accept');
                const isAccepted = acceptedIds.length > 0;

                // Identify if user has opted for "Always Reject"
                const rejectedIds = tmplIds.filter(id => res[id] === 'reject');

                if (rejectedIds.length > 0 && !silent) {
                    console.warn('[Subscribe] User rejected templates (possibly "Always Reject"):', rejectedIds);
                }

                resolve({
                    success: isAccepted,
                    res,
                    isAlwaysRejected: rejectedIds.length === tmplIds.length
                });
            },
            fail(err) {
                console.error('[Subscribe] Request Failed:', err);

                // 20004: User closed main switch in settings
                if (err.errCode === 20004) {
                    if (!silent) {
                        wx.showModal({
                            title: '提示',
                            content: '订阅通知主开关已关闭，请在设置中开启',
                            confirmText: '去开启',
                            success: (modalRes) => {
                                if (modalRes.confirm) {
                                    wx.openSetting();
                                }
                            }
                        });
                    } else {
                        console.warn('[Subscribe] Main subscription switch is OFF');
                    }
                }
                resolve({ success: false, error: err, isMainSwitchOff: err.errCode === 20004 });
            }
        });
    });
};

export const checkSubscriptionSettings = (tmplId = DEFAULT_TEMPLATE_ID) => {
    return new Promise((resolve) => {
        if (!wx.getSetting) {
            resolve(undefined);
            return;
        }

        wx.getSetting({
            withSubscriptions: true,
            success(res) {
                const itemSettings = (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings) || {};
                resolve(itemSettings[tmplId]);
            },
            fail() {
                resolve(undefined);
            }
        });
    });
};
