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

/**
 * Defense-in-depth guard for authenticated areas.
 *
 * Auth tokens live in localStorage (not readable here), so we rely on a lightweight
 * `spanglish-auth` cookie set alongside login. The API remains the authoritative gate;
 * this only keeps unauthenticated visitors from loading the admin/dashboard JS shell.
 */
export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  if (pathname.startsWith('/admin') || pathname.startsWith('/dashboard')) {
    const hasAuthCookie = request.cookies.get('spanglish-auth')?.value === '1';
    if (!hasAuthCookie) {
      const loginUrl = new URL('/login', request.url);
      loginUrl.searchParams.set('redirect', pathname);
      return NextResponse.redirect(loginUrl);
    }
  }

  return NextResponse.next();
}

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