export function requestUsesLocalAddress(request) {
  const host = String(request?.headers?.host || "").toLowerCase();
  const hostname = host.startsWith("[")
    ? host.slice(1, host.indexOf("]"))
    : host.split(":")[0];
  return hostname === "127.0.0.1" || hostname === "localhost" || hostname === "::1";
}

export function hasTailscaleIdentity(request) {
  return Boolean(
    request?.headers?.["tailscale-user-login"]
    || request?.headers?.["tailscale-user-name"]
    || request?.headers?.["tailscale-user-profile-pic"],
  );
}

export function hasPrivateNetworkAccess(request) {
  return requestUsesLocalAddress(request) || hasTailscaleIdentity(request);
}

export function hasConfiguredAccess(request, url, configuredToken = "") {
  const token = String(configuredToken || "").trim();
  if (!token) return true;
  return hasPrivateNetworkAccess(request)
    || request?.headers?.["x-private-reel-token"] === token
    || url?.searchParams?.get("token") === token;
}

export function hasConfiguredWriteAccess(request, configuredToken = "") {
  const token = String(configuredToken || "").trim();
  return hasPrivateNetworkAccess(request)
    || (Boolean(token) && request?.headers?.["x-private-reel-token"] === token);
}
