import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { SESSION_COOKIE } from "@/server/auth/constants";

// Optimistic check only: no cookie means definitely signed out, so skip
// rendering and go straight to /login. The real session check happens
// server-side in requireUser() — a present cookie proves nothing here.
export function proxy(request: NextRequest) {
  if (request.cookies.has(SESSION_COOKIE)) return NextResponse.next();

  if (request.nextUrl.pathname.startsWith("/api/")) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  return NextResponse.redirect(new URL("/login", request.url));
}

export const config = {
  // Everything except the login page, the cron endpoint (it authenticates with
  // CRON_SECRET, not a session), the public self-health probe, Next internals
  // and static files.
  matcher: ["/((?!login|api/cron/|api/health$|_next/static|_next/image|favicon.ico).*)"],
};
