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

const PROTECTED_PREFIXES = [
  "/app",
  "/transactions",
  "/rules",
  "/exports",
  "/tax",
  "/settings",
  "/profile",
];

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

  const isProtected = PROTECTED_PREFIXES.some(
    (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`)
  );

  if (!isProtected) return NextResponse.next();

  // ledgerone_auth is an HttpOnly marker cookie set by the auth API routes.
  const authCookie = req.cookies.get("ledgerone_auth");
  if (!authCookie?.value) {
    const loginUrl = new URL("/login", req.url);
    loginUrl.searchParams.set("next", pathname);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    // Run on all routes except Next.js internals and static files
    "/((?!_next/static|_next/image|favicon\.ico|api/).*)",
  ],
};
