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

const PUBLIC_PATHS = ['/login', '/api/auth', '/api/backoffice/auth'];

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Allow public paths
  if (PUBLIC_PATHS.some((p) => pathname.startsWith(p))) {
    return NextResponse.next();
  }

  // The identity backend issues the mdv_session cookie. Keep legacy names
  // accepted during migration, but do not redirect valid current sessions.
  const cookie = request.headers.get('cookie') ?? '';
  const hasSession =
    cookie.includes('mdv_session=') ||
    cookie.includes('backoffice_session=') ||
    cookie.includes('session_token=');

  if (!hasSession) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return NextResponse.next();
}

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