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

const protectedRoutes = ['/dashboard', '/profile', '/settings'];
const authRoutes = ['/auth'];
const publicRoutes = ['/'];

export function middleware(request: NextRequest) {
  const token = request.cookies.get('auth_token')?.value || 
                (typeof window !== 'undefined' ? localStorage.getItem('token') : null);
  
  const { pathname } = request.nextUrl;

  // Check if route is protected
  const isProtected = protectedRoutes.some(route => pathname.startsWith(route));
  const isAuthRoute = authRoutes.some(route => pathname.startsWith(route));
  const isPublic = publicRoutes.some(route => pathname === route);

  // Redirect to auth if accessing protected route without token
  if (isProtected && !token) {
    return NextResponse.redirect(new URL('/auth', request.url));
  }

  // Redirect to dashboard if accessing auth route with token
  if (isAuthRoute && token) {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  return NextResponse.next();
}

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