import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { jwtVerify } from 'jose';

export async function middleware(request: NextRequest) {
    const sessionToken = request.cookies.get('sessionToken')?.value;
    const adminSessionToken = request.cookies.get('adminSessionToken')?.value;

    let userIdCookie: string | undefined = undefined;
    let userRoleCookie: string | undefined = undefined;

    if (sessionToken) {
        try {
            const JWT_SECRET = process.env.JWT_SECRET || "development-temp-secret-do-not-use-in-prod";
            const secret = new TextEncoder().encode(JWT_SECRET);
            const { payload } = await jwtVerify(sessionToken, secret);
            if (payload?.userId && payload?.role) {
                userIdCookie = payload.userId as string;
                userRoleCookie = payload.role as string;
            }
        } catch {
            // Token is invalid or expired
        }
    }

    const pathname = request.nextUrl.pathname;
    const isAuthPage = pathname.startsWith('/login') || pathname.startsWith('/signup');
    const isDashboard = pathname.startsWith('/dashboard');
    const isAdminRoute = pathname.startsWith('/admin') && !pathname.startsWith('/admin/login');
    const isAdminAuthApi = pathname.startsWith('/api/admin/auth');
    const isOnboarding = pathname.startsWith('/onboarding');
    const isAuthRole = pathname.startsWith('/auth/role');

    // Add pathname to headers for server components
    const requestHeaders = new Headers(request.headers);
    requestHeaders.set('x-url', pathname);

    // 1. Redirect logged-in users away from auth pages
    if (isAuthPage && userIdCookie) {
        if (userRoleCookie === 'admin') return NextResponse.redirect(new URL('/admin', request.url));
        return NextResponse.redirect(new URL('/dashboard', request.url));
    }

    // 2. Protect /auth/role and /onboarding — must be logged in
    if ((isOnboarding || isAuthRole) && !userIdCookie) {
        return NextResponse.redirect(new URL('/login', request.url));
    }

    // 3. Handle Admin Auth Page
    if (pathname.startsWith('/admin/login') && adminSessionToken) {
        try {
            const JWT_SECRET = process.env.JWT_SECRET || "development-temp-secret-do-not-use-in-prod";
            const secret = new TextEncoder().encode(JWT_SECRET);
            await jwtVerify(adminSessionToken, secret);
            return NextResponse.redirect(new URL('/admin', request.url));
        } catch { /* Token invalid */ }
    }

    // 4. Protect /dashboard — must be logged in
    if (isDashboard && !userIdCookie) {
        return NextResponse.redirect(new URL('/login', request.url));
    }

    // 5. RBAC for dashboard sub-paths
    if (pathname.startsWith('/dashboard/employer') && userRoleCookie !== 'employer' && userRoleCookie !== 'admin') {
        return NextResponse.redirect(new URL('/dashboard', request.url));
    }

    if (pathname.startsWith('/dashboard/candidate') && userRoleCookie !== 'candidate' && userRoleCookie !== 'admin') {
        return NextResponse.redirect(new URL('/dashboard', request.url));
    }

    // 6. Protect strict Admin Routes
    if (isAdminRoute && !isAdminAuthApi) {
        if (!adminSessionToken) {
            return NextResponse.redirect(new URL('/admin/login', request.url));
        }
        try {
            const JWT_SECRET = process.env.JWT_SECRET;
            if (!JWT_SECRET) throw new Error("Missing JWT_SECRET");
            const secret = new TextEncoder().encode(JWT_SECRET);
            await jwtVerify(adminSessionToken, secret);
        } catch {
            const response = NextResponse.redirect(new URL('/admin/login', request.url));
            response.cookies.delete("adminSessionToken");
            return response;
        }
    }

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

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