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

/**
 * Edge-safe gate: everything on staff.connellypartners.com is private except the
 * login page, auth endpoints and static assets. Here we only check that a session
 * cookie exists (the edge runtime can't talk to Postgres); every page then verifies
 * the session properly via `requireSession()` in <Shell>, and API routes via `auth()`.
 */
const PUBLIC = [/^\/login$/, /^\/api\/auth\//, /^\/api\/workamajig\/sync$/, /^\/_next\//, /^\/media\//, /^\/favicon\.ico$/];

export function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;
  if (PUBLIC.some((re) => re.test(pathname))) return NextResponse.next();
  const hasSession = req.cookies.has("authjs.session-token") || req.cookies.has("__Secure-authjs.session-token");
  if (!hasSession) {
    const url = new URL("/login", req.url);
    if (pathname !== "/") url.searchParams.set("callbackUrl", pathname);
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico|media).*)"] };
