const gatewayBase = (
  process.env.NEXT_PUBLIC_API_URL ||
  process.env.PUBLIC_API_URL ||
  "http://localhost:8080/api"
).replace(/\/+$/, "");

export function gatewayUrl(path: string) {
  const normalized = path.startsWith("/") ? path : `/${path}`;
  if (gatewayBase.endsWith("/api")) {
    if (normalized === "/api") return gatewayBase;
    if (normalized.startsWith("/api/")) {
      return `${gatewayBase}${normalized.slice(3)}`;
    }
  }
  return `${gatewayBase}${normalized}`;
}

export function readAccessTokenFromRequest(request: Request): string | null {
  // 1. Prefer Authorization header forwarded by the client-side fetch
  const authHeader =
    request.headers.get("authorization") || request.headers.get("Authorization") || "";
  if (authHeader.startsWith("Bearer ")) {
    const token = authHeader.slice(7).trim();
    if (token) return token;
  }

  // 2. Fall back to legacy cookie (nxtgauge_access_token) if set
  const cookie = request.headers.get("cookie") || "";
  if (cookie) {
    const parts = cookie.split(";").map((part) => part.trim());
    const pair = parts.find((part) => part.startsWith("nxtgauge_access_token="));
    if (pair) {
      const token = pair.split("=").slice(1).join("=").trim();
      if (token) {
        try {
          return decodeURIComponent(token);
        } catch {
          return token;
        }
      }
    }
  }

  return null;
}

export function withAuthHeaders(request: Request, extra?: Record<string, string>) {
  const token = readAccessTokenFromRequest(request);
  const headers: Record<string, string> = { ...(extra || {}) };
  if (token) headers.Authorization = `Bearer ${token}`;
  return headers;
}

// Alias for forwardAuth (used in some API endpoints)
export const forwardAuth = withAuthHeaders;

// Forward cookies from request
export function forwardCookies(request: Request): Record<string, string> {
  const cookie = request.headers.get("cookie");
  if (!cookie) return {};
  return { cookie };
}
