import { auth } from "@/auth";
import { appUrl } from "@/lib/app-url";
import { NextResponse } from "next/server";

// /api/agents is machine-to-machine and carries its own bearer token, so it
// must bypass the interactive login redirect.
const PUBLIC_PATHS = ["/login", "/api/auth", "/api/agents"];
const PUBLIC_FILE = /\.(?:avif|gif|ico|jpg|jpeg|png|svg|webp)$/i;

export default auth((req) => {
  const { pathname } = req.nextUrl;
  const isPublic = PUBLIC_FILE.test(pathname) || PUBLIC_PATHS.some((p) => pathname.startsWith(p));

  if (!req.auth && !isPublic) {
    return NextResponse.redirect(appUrl("/login"));
  }
});

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:avif|gif|ico|jpg|jpeg|png|svg|webp)$).*)"],
};
