/**
 * Smart API base resolver.
 *
 * Strategy
 * ────────
 *  • Browser on localhost / 127.x / LAN IP (dev) → use the Next.js rewrite
 *    proxy `/api/backend` (same-origin, no CORS). The proxy is configured
 *    in `next.config.mjs` and auto-detects the WAMP path.
 *  • Browser on any other host (live)            → use `NEXT_PUBLIC_API_BASE_LIVE`
 *    if set, otherwise same-origin `/api/backend` via the rewrite.
 *  • SSR / middleware / edge                     → use the absolute backend
 *    URL from env (rewrites do not apply to server-side fetch).
 *
 *  • `NEXT_PUBLIC_API_BASE` — explicit override, always wins (back-compat).
 */

const DEFAULT_LOCAL_BASE = 'http://localhost/monrita-main/monrita-main/backend/public/api/v1';
const DEFAULT_LIVE_PATH = '/monrita-main/backend/public/api/v1';
// Same-origin proxy path (defined as a rewrite in next.config.mjs).
const PROXY_BASE = '/api/backend';

const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0']);

function stripTrailingSlash(url: string): string {
  return url.replace(/\/+$/, '');
}

function isLocalHostname(hostname: string): boolean {
  if (!hostname) return false;
  if (LOCAL_HOSTS.has(hostname)) return true;
  // 192.168.x.x / 10.x.x.x / 172.16-31.x.x are usually LAN dev hosts too
  if (/^192\.168\./.test(hostname)) return true;
  if (/^10\./.test(hostname)) return true;
  if (/^172\.(1[6-9]|2\d|3[01])\./.test(hostname)) return true;
  return false;
}

export function resolveApiBase(): string {
  // 1. Explicit hard override always wins (back-compat with existing setups).
  const explicit = process.env.NEXT_PUBLIC_API_BASE;
  if (explicit && explicit.trim() !== '') {
    return stripTrailingSlash(explicit);
  }

  const localBase = stripTrailingSlash(
    process.env.NEXT_PUBLIC_API_BASE_LOCAL || DEFAULT_LOCAL_BASE,
  );
  const liveBaseEnv = process.env.NEXT_PUBLIC_API_BASE_LIVE;

  // 2. Browser — prefer the same-origin proxy to dodge CORS.
  if (typeof window !== 'undefined' && window.location?.hostname) {
    const { protocol, hostname, host } = window.location;
    if (isLocalHostname(hostname)) {
      // Use Next rewrite — no CORS, path auto-detected by next.config.mjs.
      return PROXY_BASE;
    }
    if (liveBaseEnv && liveBaseEnv.trim() !== '') {
      return stripTrailingSlash(liveBaseEnv);
    }
    // Fall back to same-origin path on the live host.
    return stripTrailingSlash(`${protocol}//${host}${DEFAULT_LIVE_PATH}`);
  }

  // 3. Server / middleware / edge — use env, preferring prod base in production.
  if (process.env.NODE_ENV === 'production') {
    return stripTrailingSlash(liveBaseEnv || localBase);
  }
  return localBase;
}

export const API_BASE = resolveApiBase();
