File: //srv/rmgun_admin/admin-next/src/middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
	const { pathname } = request.nextUrl
	const sessionCookie = request.cookies.get('session')
	// Skip middleware for API routes - auth is handled at the route level via withAuth wrapper
	if (pathname.startsWith('/api')) {
		return NextResponse.next()
	}
	// Login page - redirect to dashboard if session exists
	// Actual validation happens client-side
	if (pathname === '/login') {
		if (sessionCookie) {
			return NextResponse.redirect(new URL('/dashboard', request.url))
		}
		return NextResponse.next()
	}
	// Root path - redirect based on session status
	if (pathname === '/') {
		if (sessionCookie) {
			return NextResponse.redirect(new URL('/dashboard', request.url))
		} else {
			return NextResponse.redirect(new URL('/login', request.url))
		}
	}
	// All other routes are protected - check for session cookie
	if (!sessionCookie) {
		return NextResponse.redirect(new URL('/login', request.url))
	}
	// Session cookie exists, let the request through
	// Actual validation happens in components via /api/verify
	return NextResponse.next()
}
export const config = {
	matcher: [
		/*
		 * Match all request paths except for the ones starting with:
		 * - _next/static (static files)
		 * - _next/image (image optimization files)
		 * - favicon.ico (favicon file)
		 */
		'/((?!_next/static|_next/image|favicon.ico).*)',
	],
}