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

const PUBLIC_PATHS = ["/api/health", "/api/jobs/publish-due", "/fonts/", "/_next/"];

function isPublicPath(pathname: string) {
  return PUBLIC_PATHS.some((path) => path.endsWith("/") ? pathname.startsWith(path) : pathname === path);
}

function unauthorized() {
  return new NextResponse("로그인이 필요합니다.", {
    status: 401,
    headers: { "WWW-Authenticate": 'Basic realm="Kavenix", charset="UTF-8"' },
  });
}

export function proxy(request: NextRequest) {
  if (isPublicPath(request.nextUrl.pathname)) return NextResponse.next();

  const username = process.env.APP_USERNAME;
  const password = process.env.APP_PASSWORD;
  if (!username || !password) {
    if (process.env.NODE_ENV === "development") return NextResponse.next();
    return new NextResponse("APP_USERNAME과 APP_PASSWORD를 설정해 주세요.", { status: 503 });
  }

  const authorization = request.headers.get("authorization");
  if (!authorization?.startsWith("Basic ")) return unauthorized();

  try {
    const credentials = atob(authorization.slice(6));
    const separator = credentials.indexOf(":");
    if (
      separator < 0 ||
      credentials.slice(0, separator) !== username ||
      credentials.slice(separator + 1) !== password
    ) return unauthorized();
  } catch {
    return unauthorized();
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/((?!favicon.ico|robots.txt|sitemap.xml|.*\\.(?:png|jpg|jpeg|gif|svg|webp|ico)$).*)"],
};
