import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const SESSION_COOKIE = 'tms_session';

/**
 * Keep private page routes behind an early authentication wall. The API remains
 * the authority for session validity, permissions and tenant access; this check
 * only prevents anonymous users from seeing restricted page shells by direct URL.
 */
export function middleware(request: NextRequest) {
  if (request.nextUrl.pathname === '/login') return NextResponse.next();

  if (!request.cookies.has(SESSION_COOKIE)) {
    const login = new URL('/login', request.url);
    login.searchParams.set('next', `${request.nextUrl.pathname}${request.nextUrl.search}`);
    return NextResponse.redirect(login);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!api/|_next/static|_next/image|favicon.ico|robots.txt|brand-logo.png).*)'],
};