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

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  
  // Get user data from cookie (in production, this would be a JWT token)
  const userCookie = request.cookies.get('lms_user');
  let user = null;
  
  if (userCookie) {
    try {
      user = JSON.parse(userCookie.value);
    } catch (error) {
      // Invalid cookie, clear it
      const response = NextResponse.redirect(new URL('/login', request.url));
      response.cookies.delete('lms_user');
      return response;
    }
  }

  // Public routes that don't require authentication
  const publicRoutes = ['/login', '/register', '/forgot-password', '/help', '/certificate/verify'];
  const isPublicRoute = publicRoutes.some(route => pathname.startsWith(route));

  // Static files and API routes
  if (pathname.startsWith('/_next') || pathname.startsWith('/api') || pathname.includes('.')) {
    return NextResponse.next();
  }

  // Redirect to login if accessing protected route without authentication
  if (!user && !isPublicRoute) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // Role-based access control
  if (user) {
    // Admin routes - only admin can access
    if (pathname.startsWith('/admin') && user.role !== 'admin') {
      return NextResponse.redirect(new URL('/unauthorized', request.url));
    }

    // Instructor routes - only instructors can access (if we have instructor routes)
    if (pathname.startsWith('/instructor') && user.role !== 'instructor') {
      return NextResponse.redirect(new URL('/unauthorized', request.url));
    }

    // Redirect authenticated users away from auth pages
    if (isPublicRoute && pathname !== '/help' && !pathname.startsWith('/certificate/verify')) {
      // Redirect based on role
      if (user.role === 'admin') {
        return NextResponse.redirect(new URL('/admin', request.url));
      } else if (user.role === 'student') {
        return NextResponse.redirect(new URL('/', request.url));
      } else {
        return NextResponse.redirect(new URL('/', request.url));
      }
    }
  }

  const response = NextResponse.next();
  
  // Add security headers
  response.headers.set('x-frame-options', 'DENY');
  response.headers.set('x-content-type-options', 'nosniff');
  response.headers.set('referrer-policy', 'origin-when-cross-origin');
  
  // Add role information to headers for debugging
  if (user) {
    response.headers.set('x-user-role', user.role);
    if (pathname.startsWith('/admin')) {
      response.headers.set('x-admin-route', 'true');
    }
  }
  
  return response;
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};