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

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

export function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;
  const host = req.headers.get("host") ?? "";
  const hostname = host.split(":")[0] ?? host;

  // 1. Admin Authentication Check
  if (pathname.startsWith("/admin") && pathname !== "/admin/login") {
    const adminToken = req.cookies.get("menulio_admin_token")?.value;
    if (!adminToken) {
      const loginUrl = new URL("/admin/login", req.url);
      loginUrl.searchParams.set("callbackUrl", pathname);
      return NextResponse.redirect(loginUrl);
    }
  }

  // 2. Wildcard Subdomain Routing (e.g. kebapci-ahmet.menul.io -> /menu/kebapci-ahmet)
  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

  const originalPath = pathname === "/" ? "" : 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).*)"],
};
