import { NextRequest, NextResponse } from "next/server";
import { getSessionCookieName, verifySessionToken } from "@/lib/auth";

function normalizeHost(host: string) {
  return host.split(":")[0].toLowerCase();
}

export async function proxy(request: NextRequest) {
  const pathname = request.nextUrl.pathname;
  const search = request.nextUrl.search;
  const host = normalizeHost(request.headers.get("host") || "");
  const crmHost = (process.env.CRM_HOST || "crm.workparking.ru").toLowerCase();

  const isCrmHost = host === crmHost;
  const isAdminPath = pathname.startsWith("/admin");
  const isLoginPage = pathname === "/admin/login";

  const token = request.cookies.get(getSessionCookieName())?.value;
  const isAuthed = await verifySessionToken(token);

  if (isCrmHost && pathname === "/") {
    const url = request.nextUrl.clone();
    url.pathname = isAuthed ? "/admin/leads" : "/admin/login";
    url.search = "";
    return NextResponse.redirect(url);
  }

  if (isAdminPath && !isCrmHost) {
    const url = request.nextUrl.clone();
    url.protocol = "https";
    url.hostname = crmHost;
    url.port = "";
    return NextResponse.redirect(url);
  }

  if (isAdminPath) {
    if (!isAuthed && !isLoginPage) {
      const loginUrl = request.nextUrl.clone();
      loginUrl.pathname = "/admin/login";
      loginUrl.search = `?next=${encodeURIComponent(`${pathname}${search}`)}`;
      return NextResponse.redirect(loginUrl);
    }

    if (isAuthed && isLoginPage) {
      const url = request.nextUrl.clone();
      url.pathname = "/admin/leads";
      url.search = "";
      return NextResponse.redirect(url);
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/", "/admin/:path*"],
};
