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

const MAIN_DOMAIN = process.env.MAIN_DOMAIN || "alfrednobel.edudeploy.com";

export function middleware(req: NextRequest) {
  const host = req.headers.get("host") || "";
  const cleanHost = host.split(":")[0];

  if (cleanHost === MAIN_DOMAIN || cleanHost === `www.${MAIN_DOMAIN}`) {
    return NextResponse.next();
  }

  if (!cleanHost.endsWith(`.${MAIN_DOMAIN}`)) {
    return NextResponse.next();
  }

  const pathname = req.nextUrl.pathname;
  const search = req.nextUrl.search;

  // Rewrite to the internal proxy API while preserving the original host header
  const rewriteUrl = new URL(`/api/proxy${pathname}${search}`, req.url);
  return NextResponse.rewrite(rewriteUrl);
}

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