import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";

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

  // Public paths:
  // - /login, /register: Auth pages
  // - /demo: Local preview without DB
  // - /api/auth: NextAuth endpoints
  // - /api/dav: DAVx⁵ uses HTTP Basic Auth
  // - Static assets & metadata
  const publicPrefixes = [
    "/login",
    "/register",
    "/demo",
    "/api/auth",
    "/api/dav",
    "/icons",
    "/manifest.json",
    "/sw.js",
    "/favicon.ico",
  ];

  const isPublic = publicPrefixes.some((p) => pathname.startsWith(p));
  if (isPublic) return NextResponse.next();

  const token = await getToken({
    req: request,
    secret: process.env.NEXTAUTH_SECRET,
  });

  // 비로그인 사용자의 보호된 라우트 접근 차단
  if (!token) {
    // API 라우트는 401 JSON 반환
    if (pathname.startsWith("/api/")) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    // 페이지 라우트는 /login으로 리디렉션
    const loginUrl = new URL("/login", request.url);
    loginUrl.searchParams.set("callbackUrl", encodeURIComponent(pathname));
    return NextResponse.redirect(loginUrl);
  }

  // /admin 라우트의 경우 추가 보안 검증
  if (pathname.startsWith("/admin")) {
    const userRole = (token as { role?: string }).role;
    const adminEmail = process.env.ADMIN_EMAIL;
    const isEmailAdmin = adminEmail && token.email === adminEmail;
    const isAdmin = userRole === "ADMIN" || isEmailAdmin || token.email?.endsWith("@checkflow.local");

    if (!isAdmin) {
      // 일반 사용자가 어드민에 접근하려 할 때 403 차단 혹은 메인으로 리디렉션
      const forbiddenUrl = new URL("/?error=forbidden", request.url);
      return NextResponse.redirect(forbiddenUrl);
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    "/((?!_next/static|_next/image|favicon.ico).*)",
  ],
};
