/**
 * WebSocket 基础地址
 * - HTTPS：wss://当前页面 host/alienStore/socket（不写死域名/IP，UAT/生产/测试域名通用）
 * - HTTP：优先 VITE_WS_BASE；若 env 为异名 wss 则回退 ws://当前 hostname + VITE_WS_DIRECT_PORT（默认 8000）直连 store
 * - 不配 env 的 HTTP：同上，用当前 hostname，避免写死某台 SIT IP
 */
export function getWebSocketBase(): string {
  const envBase = (import.meta.env.VITE_WS_BASE as string | undefined)?.trim();
  const directPort = String(import.meta.env.VITE_WS_DIRECT_PORT || "8000").replace(/^:/, "");

  const httpDirectWs = (hostname: string) => `ws://${hostname}:${directPort}/alienStore/socket`;

  if (typeof window !== "undefined" && window.location) {
    const isHttps = window.location.protocol === "https:";
    const host = window.location.host; // hostname + port（如 uat.ailien.shop）
    if (isHttps) {
      return `wss://${host}/alienStore/socket`;
    }
    const locHost = window.location.hostname;
    if (envBase && envBase.trim()) {
      const e = envBase.replace(/\/$/, "");
      const isLocal = locHost === "localhost" || locHost === "127.0.0.1";
      if (e.startsWith("wss://") && !isLocal) {
        try {
          const envHost = new URL(e.replace(/^wss:/, "https:")).hostname;
          if (envHost !== locHost) {
            return httpDirectWs(locHost);
          }
        } catch (_) {
          /* ignore */
        }
      }
      return e;
    }
    return httpDirectWs(locHost);
  }
  if (envBase) {
    return envBase.replace(/\/$/, "");
  }
  return `ws://127.0.0.1:${directPort}/alienStore/socket`;
}
