import { NextRequest, NextResponse } from "next/server";
import { resolveAdminHost, resolveManageHost, resolveRootDomain, resolveWebmailHost, stripPort } from "@/lib/site-config";

export function middleware(request: NextRequest) {
  const host = stripPort(request.headers.get("host") || request.nextUrl.hostname);
  const pathname = request.nextUrl.pathname;
  if (/\.[a-z0-9]+$/i.test(pathname)) {
    return NextResponse.next();
  }
  const protocol = stripPort(request.headers.get("x-forwarded-proto") || request.nextUrl.protocol.replace(":", "")) || "https";
  const url = new URL(pathname + request.nextUrl.search, `${protocol}://${host}`);
  const centralMailHost = resolveWebmailHost();
  const manageHost = resolveManageHost();
  const adminHost = resolveAdminHost();
  const isCentralMailHost = Boolean(centralMailHost) && host === centralMailHost;
  const tenantRoutesEnabled = process.env.NEXT_PUBLIC_ENABLE_TENANT_ROUTES === "true";

  if (resolveRootDomain() && host === stripPort(resolveRootDomain())) {
    url.hostname = centralMailHost;
    url.protocol = "https";
    return NextResponse.redirect(url);
  }

  if (host && manageHost && host === manageHost) {
    if (url.pathname === "/admin") {
      url.pathname = "/login";
      return NextResponse.redirect(url);
    }
    return NextResponse.next();
  }

  if (host && adminHost && host === adminHost) {
    if (url.pathname === "/") {
      const rewriteUrl = request.nextUrl.clone();
      rewriteUrl.protocol = "http:";
      rewriteUrl.pathname = "/admin";
      return NextResponse.rewrite(rewriteUrl);
    }
    return NextResponse.next();
  }

  if (tenantRoutesEnabled && host.startsWith("mail.") && !isCentralMailHost && centralMailHost) {
    const tenant = host.slice("mail.".length);
    if (!tenant) return NextResponse.next();

    const rewriteUrl = request.nextUrl.clone();
    rewriteUrl.protocol = "http:";
    rewriteUrl.pathname = `/t/${encodeURIComponent(tenant)}${url.pathname === "/" ? "" : url.pathname}`;
    // Keep custom domains in the browser while routing them internally to the
    // tenant page. A redirect exposes the central host to every customer.
    return NextResponse.rewrite(rewriteUrl);
  }

  return NextResponse.next();
}

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