/**
 * Base-path / public-URL helpers so the same build can be served at the domain root
 * OR under a subfolder (e.g. /product-ai-automation) purely via env — no code changes.
 *
 *  - BASE_PATH (build-time): the URL path prefix. Drives Next's basePath + assetPrefix
 *    in next.config, and is exposed to the client as NEXT_PUBLIC_BASE_PATH. Empty = root.
 *  - APP_URL (runtime): the full public base URL incl. any subpath, e.g.
 *    "https://poc.digt.ch/product-ai-automation" — used to build the exact Google OAuth
 *    callback URL behind a reverse proxy. Empty = derive from the incoming request.
 *
 * Next's basePath already prefixes <Link>, the router and /_next assets automatically.
 * These helpers cover what it does NOT: raw fetch(), plain <a href>, window.location,
 * and server-side redirects / the OAuth redirect_uri.
 */
export const BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH ?? "";
export const APP_URL = (process.env.APP_URL ?? "").replace(/\/$/, "");

/** Prefix an app-absolute path ("/x") with BASE_PATH. Idempotent; a no-op at root. */
export function withBase(path: string): string {
  if (BASE_PATH === "" || !path.startsWith("/")) return path;
  if (path === BASE_PATH || path.startsWith(BASE_PATH + "/")) return path; // already prefixed
  return BASE_PATH + path;
}

/** Cookie path that scopes session cookies to this app (isolates sibling sub-apps). */
export const COOKIE_PATH = BASE_PATH || "/";

/** Exact public Google OAuth callback URL — APP_URL when set (proxy-safe), else derived. */
export function googleCallbackUrl(req: { url: string }): string {
  if (APP_URL) return `${APP_URL}/api/auth/google/callback`;

  return new URL(withBase("/api/auth/google/callback"), req.url).toString();
}
