/** doctor-wx-auth 请求与绑定状态查询共用的登录态解析（无 API 依赖，避免与 common/js/index 循环引用） */

export const ADMIN_TOKEN_KEYS = {
	platform_admin: 'platform_admin_token',
	salesperson: 'salesperson_token',
	clinic_salesperson: 'clinic_salesperson_token',
	clinic_admin: 'clinic_admin_token',
};

export const ADMIN_USER_KEYS = {
	platform_admin: 'platform_admin_user',
	salesperson: 'salesperson_user',
	clinic_salesperson: 'clinic_salesperson_user',
	clinic_admin: 'clinic_admin_user',
};

/** 当前有效的 admin loginMode（须同时有 token） */
export function resolveActiveAdminLoginMode() {
	const stored = uni.getStorageSync('loginMode');
	if (stored && ADMIN_TOKEN_KEYS[stored] && uni.getStorageSync(ADMIN_TOKEN_KEYS[stored])) {
		return stored;
	}
	return '';
}

/** doctor-wx-auth 接口应使用的 token：优先当前 loginMode 对应 admin，否则医生/药师 token，不 fallback 其它 admin token */
export function resolveDoctorWxAuthToken() {
	const loginMode = resolveActiveAdminLoginMode();
	if (loginMode) {
		return uni.getStorageSync(ADMIN_TOKEN_KEYS[loginMode]) || '';
	}
	return uni.getStorageSync('token') || '';
}

/** 当前登录上下文（手机号 + 账号维度，供 wx-bind-status 等） */
export function getCurrentLoginContext() {
	const loginMode = resolveActiveAdminLoginMode();
	if (loginMode) {
		const user = uni.getStorageSync(ADMIN_USER_KEYS[loginMode]) || {};
		return {
			phone: String(user.phone || '').trim(),
			account_type: 'admin',
			account_id: Number(user.id || 0),
			token: uni.getStorageSync(ADMIN_TOKEN_KEYS[loginMode]) || '',
		};
	}

	const loginInfo = uni.getStorageSync('loginInfo') || uni.getStorageSync('logInfo') || {};
	return {
		phone: String(loginInfo.mobile || loginInfo.phone || '').trim(),
		account_type: 'service_user',
		account_id: Number(loginInfo.id || uni.getStorageSync('login_id') || 0),
		token: uni.getStorageSync('token') || '',
	};
}
