/**
 * Request WeChat Mini Program Subscription Message
 * Template ID: R7fh3NDpuV8DYqI83HpEQvC8mLJy5xMWFl1qeGN9JIo
 */
const TEMPLATE_ID = 'R7fh3NDpuV8DYqI83HpEQvC8mLJy5xMWFl1qeGN9JIo';

export const requestSubscription = () => {
    return new Promise((resolve) => {
        // Check if subscription capability is available (basic check)
        if (!wx.requestSubscribeMessage) {
            console.warn('Current version does not support subscribe message');
            resolve({ success: false, errMsg: 'Not supported' });
            return;
        }

        wx.requestSubscribeMessage({
            tmplIds: [TEMPLATE_ID],
            success(res) {
                if (res[TEMPLATE_ID] === 'accept') {
                    console.log('Subscription accepted');
                    resolve({ success: true, status: 'accept' });
                } else {
                    console.log('Subscription rejected or other status', res[TEMPLATE_ID]);
                    resolve({ success: false, status: res[TEMPLATE_ID] });
                }
            },
            fail(err) {
                console.error('Subscription failed', err);
                resolve({ success: false, errMsg: err.errMsg });
            }
        });
    });
};

export const checkSubscriptionSettings = () => {
    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[TEMPLATE_ID]);
            },
            fail() {
                resolve(undefined);
            }
        });
    });
};
