import { withAuth } from 'next-auth/middleware';
import { NextResponse } from 'next/server';

export default withAuth(
    function middleware(req) {
        // Authenticated user hitting /login → redirect to home
        if (req.nextUrl.pathname === '/login') {
            return NextResponse.redirect(new URL('/', req.url));
        }
        return NextResponse.next();
    },
    {
        callbacks: {
            // Return true = allow, false = redirect to signIn page
            authorized({ token }) {
                return !!token;
            },
        },
        pages: {
            signIn: '/login',
        },
    }
);

// Apply to every route except NextAuth internals, static files, and the login page itself
export const config = {
    matcher: [
        '/((?!login|api/auth|_next/static|_next/image|favicon\\.ico).*)',
    ],
};
