/**
 * Build a URL for the external Orion API.
 * Base URL comes from VITE_API_URL_ORION; the path is configured per component.
 */
export function orionExternalApiUrl(path: string, base?: string): string {
  const apiBase = (base ?? (import.meta.env.VITE_API_URL_ORION as string | undefined) ?? "").trim();
  const normalizedPath = path.startsWith("/") ? path.slice(1) : path;

  if (!apiBase) {
    throw new Error("Orion API base URL is not configured. Set VITE_API_URL_ORION.");
  }

  if (!normalizedPath) {
    throw new Error("Orion API path is required.");
  }

  const normalizedBase = apiBase.replace(/\/+$/, "");
  return `${normalizedBase}/${normalizedPath}`;
}

const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);

function isLocalDevHostPair(a: string, b: string): boolean {
  return LOCAL_HOSTS.has(a) && LOCAL_HOSTS.has(b);
}

/**
 * True when the configured API base targets the same app server as the current page.
 * Uses a relative path so session cookies stay same-origin (avoids localhost vs 127.0.0.1 splits).
 */
function shouldUseRelativeApiPath(configuredBase: string): boolean {
  if (typeof window === "undefined") {
    return false;
  }

  try {
    const resolved = new URL(configuredBase, window.location.origin);
    if (resolved.origin === window.location.origin) {
      return true;
    }

    const samePort =
      resolved.port === window.location.port ||
      (!resolved.port && !window.location.port) ||
      (resolved.port === "8000" && window.location.port === "8000");

    return samePort && isLocalDevHostPair(resolved.hostname, window.location.hostname);
  } catch {
    return false;
  }
}

/**
 * Join an API base URL with a path such as `/api/site-settings`.
 * Strips duplicate `/api` when the base already ends with `/api`.
 * Prefers same-origin relative paths so Laravel session cookies are always sent.
 */
export function apiUrl(path: string, base?: string): string {
  const normalizedPath = path.startsWith("/") ? path : `/${path}`;
  const configuredBase = (base ?? import.meta.env.VITE_API_URL ?? "").trim();

  if (!configuredBase || shouldUseRelativeApiPath(configuredBase)) {
    return normalizedPath;
  }

  const normalizedBase = configuredBase.replace(/\/+$/, "");

  if (normalizedBase.endsWith("/api") && normalizedPath.startsWith("/api")) {
    return `${normalizedBase}${normalizedPath.slice(4)}`;
  }

  return `${normalizedBase}${normalizedPath}`;
}

export function adminApiUrl(path: string): string {
  return apiUrl(path, (import.meta.env.VITE_ADMIN_API_URL as string | undefined) ?? "");
}
