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

// The cookie is NOT httpOnly so the Axios interceptor (browser-side) can read it for
// Bearer auth injection. This is a deliberate trade-off: the token is accessible to
// JS running on the same origin, which is acceptable for an installer-only internal app.
// Do NOT use this pattern for consumer-facing applications.
const TOKEN_COOKIE = 'auth_token';

export function proxy(request: NextRequest) {
  const token = request.cookies.get(TOKEN_COOKIE)?.value;
  const { pathname } = request.nextUrl;

  if (pathname.startsWith('/installation') && !token) {
    const loginUrl = request.nextUrl.clone();
    loginUrl.pathname = '/login';
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/installation/:path*'],
};
