import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getAppMode, isPublicRoute } from './lib/mode';

/**
 * Next.js middleware for route protection based on application mode
 *
 * In pre-launch mode:
 * - Only allows access to public routes (/, /api/signup)
 * - Returns 404 for all other routes
 *
 * In alpha mode:
 * - All routes are accessible
 */
export function middleware(request: NextRequest) {
  const mode = getAppMode();
  const { pathname } = request.nextUrl;
  
  // In alpha mode, allow all routes
  if (mode === 'alpha') {
    return NextResponse.next();
  }
  
  // In pre-launch mode, check if route is public
  if (isPublicRoute(pathname)) {
    return NextResponse.next();
  }
  
  // Protected route in pre-launch mode - return 404
  return new NextResponse(null, {
    status: 404,
    statusText: 'Not Found',
  });
}

/**
 * Configure which routes the middleware should run on
 * Excludes Next.js internal routes and static assets
 */
export const config = {
  matcher: [
    /*
     * Match all request paths except:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * - public folder files
     */
    '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|mp4|webm|mov|avi)$).*)',
  ],
};