import { parentMpLogin } from '@/api/login';
import { getCache, setCache } from '@/utils/cache';

let openidPromise: Promise<string> | null = null;

const readCachedOpenid = () => {
    const cachedOpenid = getCache('wxOpenid');
    if (cachedOpenid) return String(cachedOpenid);

    const userInfo = getCache('userInfo');
    if (userInfo && typeof userInfo === 'object') {
        const openid = userInfo.openid || userInfo.openId || userInfo.wxOpenid;
        if (openid) return String(openid);
    }

    return '';
};

/** 获取当前微信 openid，优先读缓存，否则通过 uni.login + mpLogin 换取并持久化 */
export const getWxOpenid = async (): Promise<string> => {
    const cached = readCachedOpenid();
    if (cached) return cached;

    if (!openidPromise) {
        openidPromise = (async () => {
            const loginRes = await new Promise<UniApp.LoginRes>((resolve, reject) => {
                uni.login({
                    provider: 'weixin',
                    success: resolve,
                    fail: reject,
                });
            });

            const code = loginRes?.code || '';
            if (!code) {
                throw new Error('获取微信 code 失败');
            }

            const res = await parentMpLogin(code);
            const openid = res?.data?.wxUser?.openid || '';
            if (!openid) {
                throw new Error('获取微信 openid 失败');
            }

            setCache('wxOpenid', openid);
            return openid;
        })().finally(() => {
            openidPromise = null;
        });
    }

    return openidPromise;
};

export const cacheWxOpenid = (openid?: string) => {
    if (!openid) return;
    setCache('wxOpenid', openid);
};
