import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';

export async function proxy(req: NextRequest) {
    const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
    const path = req.nextUrl.pathname;

    // Pass pathname as header so layout.tsx can hide navbar
    const requestHeaders = new Headers(req.headers);
    requestHeaders.set('x-pathname', path);

    if (!token && (
        path.startsWith('/super-admin') ||
        path.startsWith('/admin')
    )) {
        return NextResponse.redirect(new URL('/my-account', req.url));
    }

    if (token) {
        const role = token.role as number;
        if (role === 1 && path.startsWith('/super-admin')) {
            return NextResponse.redirect(new URL('/admin', req.url));
        }
        if (role === 2 && (path.startsWith('/super-admin') || path.startsWith('/admin'))) {
            return NextResponse.redirect(new URL('/my-account', req.url));
        }
    }

    return NextResponse.next({
        request: { headers: requestHeaders },
    });
}

export const config = {
    matcher: ['/super-admin/:path*', '/admin/:path*', '/my-account/:path*'],
};