import NextAuth from "next-auth";
import { NextResponse } from "next/server";
import { authConfig } from "@/lib/auth/auth.config";

// Edge-Instanz nur zum Lesen des JWT — keine DB, kein Argon2.
const { auth } = NextAuth(authConfig);

// Öffentlich erreichbare Pfade (ohne Login).
// `/api/creators/sync` prüft selbst ein Secret (für den täglichen Scheduler).
const PUBLIC_PREFIXES = ["/login", "/reset", "/api/auth", "/api/creators/sync"];

function isPublic(pathname: string): boolean {
  return PUBLIC_PREFIXES.some(
    (p) => pathname === p || pathname.startsWith(`${p}/`),
  );
}

export default auth((req) => {
  const { pathname, search } = req.nextUrl;
  const isLoggedIn = Boolean(req.auth);

  // Eingeloggt + Login/Reset aufgerufen → ins Dashboard.
  if (isLoggedIn && (pathname === "/login" || pathname.startsWith("/reset"))) {
    return NextResponse.redirect(new URL("/dashboard", req.nextUrl));
  }

  if (isPublic(pathname)) return NextResponse.next();

  // Geschützter Bereich ohne Login → zur Anmeldung (mit Rücksprungziel).
  if (!isLoggedIn) {
    const loginUrl = new URL("/login", req.nextUrl);
    if (pathname !== "/") {
      loginUrl.searchParams.set("callbackUrl", `${pathname}${search}`);
    }
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
});

// Gilt für alle Routen außer statischen Assets & Auth-API.
export const config = {
  matcher: [
    "/((?!api/auth|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|woff2?)$).*)",
  ],
};
