export function pwaAllowedHosts(env = process.env) {
  const configuredHosts = String(env.CODE_REMOTE_MANAGER_PWA_ALLOWED_HOSTS || "")
    .split(",")
    .map((host) => host.trim())
    .filter(Boolean);

  return [...new Set(configuredHosts)];
}

function firstHeader(value) {
  return Array.isArray(value) ? value[0] : value;
}

export function pwaProxyOrigin(request, env = process.env) {
  const host = String(firstHeader(request?.headers?.host) || "").trim().toLowerCase();
  if (!host) return "";

  let parsed;
  try {
    parsed = new URL(`http://${host}`);
  } catch {
    return "";
  }
  if (parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash || parsed.host !== host) return "";

  const hostname = parsed.hostname.toLowerCase();
  const local = hostname === "127.0.0.1" || hostname === "localhost";
  if (!local && !pwaAllowedHosts(env).some((allowed) => allowed.toLowerCase() === hostname)) return "";

  const forwarded = String(firstHeader(request?.headers?.["x-forwarded-proto"]) || "")
    .split(",", 1)[0]
    .trim()
    .toLowerCase();
  if (forwarded && forwarded !== "http" && forwarded !== "https") return "";
  const protocol = forwarded || (local ? "http" : "https");
  return `${protocol}://${host}`;
}

export function isPwaEventStreamRequest(method, path = "") {
  return method === "GET" && /^\/(?:api\/)?sessions\/(?:events|[^/?]+\/events)(?:\?|$)/.test(path);
}
