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

const ROOT_DOMAIN = process.env.ROOT_DOMAIN ?? "menul.io";

// Wildcard subdomain routing: kebapci-ahmet.menul.io -> /menu/kebapci-ahmet
// Custom domains resolve here too once verified (PRD §11).
export function middleware(req: NextRequest) {
  const host = req.headers.get("host") ?? "";
  const hostname = host.split(":")[0] ?? host;

  const isRootDomain = hostname === ROOT_DOMAIN || hostname === `www.${ROOT_DOMAIN}`;
  if (isRootDomain || hostname === "localhost") {
    return NextResponse.next();
  }

  const subdomain = hostname.endsWith(`.${ROOT_DOMAIN}`)
    ? hostname.replace(`.${ROOT_DOMAIN}`, "")
    : hostname; // custom domain — resolved to a slug via domains table at render time

  // On the root path, req.nextUrl.pathname is "/" — appending it as-is would
  // rewrite to "/menu/<slug>/" (trailing slash), which the [slug] dynamic
  // route does not match. Only append the original path when it's non-root.
  const originalPath = req.nextUrl.pathname === "/" ? "" : req.nextUrl.pathname;

  const url = req.nextUrl.clone();
  url.pathname = `/menu/${subdomain}${originalPath}`;
  return NextResponse.rewrite(url);
}

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