import { NextResponse, type NextRequest } from "next/server";

/**
 * Custom domains: requests whose Host is not the app's own domain are served the landing page attached to that
 * domain (PAGE-004). App routes, APIs and static assets pass through untouched.
 */
/** EXTRA_APP_HOSTS: comma-separated white-label login domains that should serve the app itself. */
const APP_HOSTS = new Set(
  [process.env.APP_URL, process.env.NEXT_PUBLIC_APP_URL, process.env.VERCEL_URL && `https://${process.env.VERCEL_URL}`, process.env.VERCEL_PROJECT_PRODUCTION_URL && `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`]
    .concat((process.env.EXTRA_APP_HOSTS ?? "").split(",").map((h) => h.trim() && `https://${h.trim()}`))
    .filter(Boolean).map((u) => { try { return new URL(String(u)).host; } catch { return String(u); } }),
);

export function middleware(req: NextRequest) {
  const host = (req.headers.get("x-forwarded-host") ?? req.headers.get("host") ?? "").toLowerCase();
  const bare = host.split(":")[0]!;
  const isApp = APP_HOSTS.has(host) || bare === "localhost" || bare === "127.0.0.1" || bare.endsWith(".vercel.app") || bare.endsWith(".localhost");
  if (isApp) {
    // the app layout reads the path to decide paywall / plan gating (server components can't see the URL otherwise)
    const h = new Headers(req.headers);
    h.set("x-pathname", req.nextUrl.pathname);
    return NextResponse.next({ request: { headers: h } });
  }
  const p = req.nextUrl.pathname;
  if (p.startsWith("/api/") || p.startsWith("/_next/") || p === "/t.js" || p.startsWith("/icon")) return NextResponse.next();
  if (p !== "/" && p !== "") return NextResponse.next();
  const url = req.nextUrl.clone();
  url.pathname = `/d/${encodeURIComponent(bare)}`;
  return NextResponse.rewrite(url);
}

export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"] };
