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

const MAIL_HOST = "mail.officialsite.kr";
const PUBLIC_HOST = "officialsite.kr";
const WWW_PUBLIC_HOST = "www.officialsite.kr";
const PUBLIC_SITE_ORIGIN = "https://officialsite.kr";
const MAIL_APP_ORIGIN = "https://mail.officialsite.kr";
const PUBLIC_SITE_PATHS = [
  "/business-email",
  "/domain-email",
  "/ai-email-summary",
  "/team-mailbox",
  "/secure-business-email",
  "/faq",
  "/guide",
  "/terms",
  "/privacy",
];
const MAIL_APP_PATHS = [
  "/api",
  "/dashboard",
  "/find-id",
  "/kavenix",
  "/login",
  "/mail",
  "/mail-setup",
  "/payments",
  "/reset-password",
  "/signup",
];
const MAIL_HOST_ROBOTS = [
  "User-agent: *",
  "Disallow: /",
  "",
  `Sitemap: ${PUBLIC_SITE_ORIGIN}/sitemap.xml`,
  "",
].join("\n");

function isPathMatch(pathname: string, paths: string[]) {
  return paths.some(
    (path) => pathname === path || pathname.startsWith(`${path}/`),
  );
}

function isPublicSitePath(pathname: string) {
  return isPathMatch(pathname, PUBLIC_SITE_PATHS);
}

function isMailAppPath(pathname: string) {
  return isPathMatch(pathname, MAIL_APP_PATHS);
}

function redirectToOrigin(nextUrl: NextRequest["nextUrl"], origin: string) {
  const url = new URL(nextUrl.pathname, origin);
  url.search = nextUrl.search;
  return NextResponse.redirect(url, 308);
}

export function proxy(request: NextRequest) {
  const { nextUrl, headers } = request;
  const host = headers.get("host")?.split(":")[0]?.toLowerCase() ?? "";

  if (host === WWW_PUBLIC_HOST) {
    return redirectToOrigin(
      nextUrl,
      isMailAppPath(nextUrl.pathname) ? MAIL_APP_ORIGIN : PUBLIC_SITE_ORIGIN,
    );
  }

  if (host === PUBLIC_HOST && isMailAppPath(nextUrl.pathname)) {
    return redirectToOrigin(nextUrl, MAIL_APP_ORIGIN);
  }

  if (host === MAIL_HOST && nextUrl.pathname === "/robots.txt") {
    return new NextResponse(MAIL_HOST_ROBOTS, {
      headers: {
        "content-type": "text/plain; charset=utf-8",
      },
    });
  }

  if (host === MAIL_HOST && nextUrl.pathname === "/sitemap.xml") {
    return redirectToOrigin(nextUrl, PUBLIC_SITE_ORIGIN);
  }

  if (
    host === MAIL_HOST &&
    (nextUrl.pathname === "/" || isPublicSitePath(nextUrl.pathname))
  ) {
    return redirectToOrigin(nextUrl, PUBLIC_SITE_ORIGIN);
  }

  if (host === MAIL_HOST && isMailAppPath(nextUrl.pathname)) {
    const response = NextResponse.next();
    response.headers.set("X-Robots-Tag", "noindex, nofollow, noarchive");
    return response;
  }

  return NextResponse.next();
}

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