// proxy.ts — Next 16 "proxy" (formerly middleware). Optimistic auth gate:
// redirect to /login when no session cookie is present. Real validation
// happens server-side via getActiveOrgId/getActiveUserId.
import { getSessionCookie } from "better-auth/cookies";
import { type NextRequest, NextResponse } from "next/server";

export function proxy(request: NextRequest) {
  const cookie = getSessionCookie(request);
  if (!cookie) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  // Work-in-progress gating lives in the gated route segment layouts (see
  // src/lib/feature-status), NOT here: a proxy rewrite to /under-construction
  // made Next self-fetch the RSC over https://localhost:3000 behind the TLS
  // proxy → ECONNREFUSED → 500. The layout renders the placeholder in-place.
  return NextResponse.next();
}

export const config = {
  // Run on everything EXCEPT login/signup/password-reset, the 2FA challenge,
  // the public pricing page, the auth API, the worker broker and the MCP
  // endpoint (both Bearer-token authed with their own fail-closed guards and NO
  // session cookie — the optimistic cookie check here would otherwise 307 them
  // to /login and break external clients), and Next internals.
  //
  // `two-factor` MUST be exempt: after the password step a 2FA account has NO
  // full session cookie yet (only the short-lived two-factor cookie), so the
  // optimistic check would bounce /two-factor → /login, where re-entering the
  // password redirects back to /two-factor → /login… an infinite login loop.
  // Affects every 2FA user (email+password AND OAuth/Google → 2FA).
  //
  // `logo` MUST be exempt: the brand logo (public/logo/*.png) is rendered on
  // the UNauthenticated /login page. Without a session cookie the optimistic
  // gate would redirect /logo/*.png → /login, so the <img> receives HTML
  // instead of a PNG (naturalWidth 0, broken image). favicon.ico is exempt for
  // the same reason.
  //
  // `flags` MUST be exempt: country flag SVGs (public/flags/*.svg) are served
  // as static assets by the <Flag> component, including on UNauthenticated
  // pages. Without the exemption the optimistic gate would redirect
  // /flags/*.svg → /login and the <img> would receive HTML instead of an SVG.
  matcher: [
    "/((?!login|signup|two-factor|forgot-password|reset-password|accept-invitation|pricing|api/auth|api/worker|api/mcp|_next/static|_next/image|favicon.ico|logo|flags).*)",
  ],
};
