import { loginByWechatCode } from '@/api/auth';
import { authStorage } from '@/utils/storage';

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

const getWechatCode = () => {
	// #ifdef MP-WEIXIN
	return new Promise<string>((resolve, reject) => {
		uni.login({
			success: (result) => {
				if (!result.code) {
					reject(new Error('微信登录凭证获取失败'));
					return;
				}
				resolve(result.code);
			},
			fail: () => reject(new Error('微信登录凭证获取失败'))
		});
	});
	// #endif

	// #ifndef MP-WEIXIN
	return Promise.reject(new Error('当前端暂不支持微信无感登录'));
	// #endif
};

export const ensureLogin = () => {
	if (loginPromise) return loginPromise;

	const pendingLogin = (async () => {
		const code = await getWechatCode();
		const result = await loginByWechatCode(code);
		const token = result?.data?.token;

		if (Number(result?.code) !== 200 || !token) {
			throw new Error(result?.msg || '登录失败');
		}

		authStorage.setToken(token, Number(result.data?.expires_in || 0));
		return token;
	})();

	loginPromise = pendingLogin.finally(() => {
		loginPromise = null;
	});

	return loginPromise;
};
