/**
 * 小程序 WebView 分享 / page_path 里可能携带上一用户的 unionid、openid、status 等，
 * 接收方打开后会导致串号或误登。从「路径 + 查询」字符串中剥离这些参数后再交给 vue-router。
 */
const WEBVIEW_IDENTITY_QUERY_KEYS = [
  'unionid',
  'openid',
  'status',
  'nickName',
  'avatarUrl',
  'ts',
  'scene',
] as const;

export function sanitizeMiniProgramWebViewPathForRouter(decodedPathOrUrl: string): string {
  const raw = decodedPathOrUrl.trim();
  if (!raw || raw === '/') {
    return '/';
  }
  let pathPart = raw;
  let search = '';
  const q = raw.indexOf('?');
  if (q === 0) {
    pathPart = '/';
    search = raw.slice(1);
  } else if (q > 0) {
    pathPart = raw.slice(0, q) || '/';
    search = raw.slice(q + 1);
  }
  if (!pathPart.startsWith('/')) {
    pathPart = `/${pathPart}`;
  }
  if (!search) {
    return pathPart;
  }
  const params = new URLSearchParams(search);
  for (const key of WEBVIEW_IDENTITY_QUERY_KEYS) {
    params.delete(key);
  }
  const rest = params.toString();
  return rest ? `${pathPart}?${rest}` : pathPart;
}
