import { NextResponse, type NextRequest } from 'next/server';
import { createServerClient } from '@/shared/db/supabase-client';

// --- ASA GENERATED START ---
// Auth middleware — session check, redirect to /login for protected routes.
// --- ASA GENERATED END ---

// --- USER CODE START ---

const PUBLIC_ROUTES = ['/auth/login', '/auth/register', '/auth/reset-password', '/'];

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

  // Allow public routes
  if (PUBLIC_ROUTES.some((route) => pathname.startsWith(route))) {
    return NextResponse.next();
  }

  // Check session
  const response = NextResponse.next();
  const supabase = createServerClient({
    getAll: () => request.cookies.getAll(),
    setAll: (cookies: any[]) => {
      cookies.forEach(({ name, value, options }) => {
        response.cookies.set(name, value, options);
      });
    },
  });

  const { data: { user } } = await supabase.auth.getUser();

  if (!user) {
    const loginUrl = new URL('/auth/login', request.url);
    loginUrl.searchParams.set('redirect', pathname);
    return NextResponse.redirect(loginUrl);
  }

  return response;
}

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

// --- USER CODE END ---
