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

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

const getLoginCode = () => {
	// #ifdef MP-WEIXIN || MP-ALIPAY
	return new Promise<string>((resolve, reject) => {
		uni.login({
			// #ifdef MP-ALIPAY
			provider: 'alipay',
			scopes: 'auth_base',
			// #endif
			success: (result) => {
				const code = result.code || (result as any).authCode;
				if (!code) {
					reject(new Error('登录凭证获取失败'));
					return;
				}
				resolve(code);
			},
			fail: () => reject(new Error('登录凭证获取失败'))
		});
	});
	// #endif

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

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

	const pendingLogin = (async () => {
		const code = await getLoginCode();
		const result = await loginByCode(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;
};
