import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { isAuthenticated, getUserRole } from '@/lib/auth';

// Define protected routes and their corresponding roles
const protectedRoutes: { [key: string]: string[] } = {
  '/admin': ['admin', 'manager', 'staff', 'accountant'],
  '/investor': ['investor'],
  '/swapstation': ['swapstation'],
  '/merchant': ['merchant'],
  '/biker': ['biker'],
};

// Define public routes that don't require authentication
const publicRoutes = ['/login', '/', '/api/', '/_next/'];

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

  // Check if the route is public
  const isPublicRoute = publicRoutes.some(route =>
    pathname.startsWith(route)
  );

  if (isPublicRoute) {
    return NextResponse.next();
  }

  // Check if the user is authenticated
  const isAuth = isAuthenticated();

  // If trying to access login page while authenticated, redirect to appropriate dashboard
  if (pathname === '/login' && isAuth) {
    const role = getUserRole();
    if (!role) {
      // If no role found, logout and redirect to login
      // In a real app, you'd clear the session and redirect
      // For demo, we'll just redirect to login (but this would cause a loop, so we'll go to home)
      return NextResponse.redirect(new URL('/', request.url));
    }

    // Redirect based on role
    let redirectUrl = '/'; // default

    switch (role) {
      case 'admin':
      case 'manager':
      case 'staff':
        redirectUrl = '/admin';
        break;
      case 'accountant':
        redirectUrl = '/admin/accounting';
        break;
      case 'investor':
        redirectUrl = '/investor';
        break;
      case 'biker':
        redirectUrl = '/';
        break;
      case 'swapstation':
        redirectUrl = '/swapstation';
        break;
      case 'merchant':
        redirectUrl = '/merchant';
        break;
      default:
        redirectUrl = '/';
    }

    return NextResponse.redirect(new URL(redirectUrl, request.url));
  }

  // If not authenticated and trying to access a protected route, redirect to login
  if (!isAuth) {
    // Check if the route is protected
    const isProtectedRoute = Object.keys(protectedRoutes).some(prefix =>
      pathname.startsWith(prefix)
    );

    if (isProtectedRoute) {
      return NextResponse.redirect(new URL('/login', request.url));
    }
  }

  // If authenticated, check if the user has access to the specific route
  if (isAuth) {
    const role = getUserRole();
    if (role) {
      // Check if the route is protected and if the user's role is allowed
      for (const [prefix, allowedRoles] of Object.entries(protectedRoutes)) {
        if (pathname.startsWith(prefix) && !allowedRoles.includes(role)) {
          // User is authenticated but doesn't have permission for this route
          // Redirect to home or show an error - for demo, we'll redirect to home
          return NextResponse.redirect(new URL('/', request.url));
        }
      }
    }
  }

  return NextResponse.next();
}

// Configure middleware to run on specific paths
export const config = {
  matcher: [
    /*
     * Match all request paths except:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * - public folder
     */
    '/((?!_next/static|_next/image|favicon.ico|public).*)',
  ],
};