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

import { ADMIN_TOKEN_STORAGE_KEY } from "@/lib/admin-token-constants";
import { readAdminTokenFromCookieString } from "@/lib/admin-token-cookie";

const ADMIN_LOGIN_PATH = "/admin/login";

function isAdminLoginPath(pathname: string): boolean {
  return pathname === ADMIN_LOGIN_PATH || pathname.startsWith(`${ADMIN_LOGIN_PATH}/`);
}

function readTokenFromRequest(request: NextRequest): string | null {
  const fromCookie = request.cookies.get(ADMIN_TOKEN_STORAGE_KEY)?.value?.trim();
  if (fromCookie) {
    return fromCookie;
  }

  return readAdminTokenFromCookieString(request.headers.get("cookie"));
}

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  if (!pathname.startsWith("/admin")) {
    return NextResponse.next();
  }

  if (isAdminLoginPath(pathname)) {
    return NextResponse.next();
  }

  const token = readTokenFromRequest(request);
  if (!token) {
    const loginUrl = request.nextUrl.clone();
    loginUrl.pathname = ADMIN_LOGIN_PATH;
    loginUrl.search = "";
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

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