import { NextRequest, NextResponse } from 'next/server';
import { verifyToken, TokenPayload } from './auth';

export interface AuthenticatedRequest extends NextRequest {
    user?: TokenPayload;
}

type RouteContext = {
    params?: Promise<unknown> | unknown;
};

/**
 * Middleware to authenticate requests using JWT
 */
export function authenticateToken<T extends RouteContext = RouteContext>(
    handler: (req: AuthenticatedRequest, context?: T) => Promise<NextResponse>
) {
    return async (req: AuthenticatedRequest, context?: T) => {
        try {
            const authHeader = req.headers.get('authorization');
            const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

            if (!token) {
                return NextResponse.json(
                    { error: 'Authentication required' },
                    { status: 401 }
                );
            }

            const user = verifyToken(token);
            req.user = user;

            return handler(req, context);
        } catch {
            return NextResponse.json(
                { error: 'Invalid or expired token' },
                { status: 403 }
            );
        }
    };
}

/**
 * Middleware to require admin role
 */
export function requireAdmin<T extends RouteContext = RouteContext>(
    handler: (req: AuthenticatedRequest, context?: T) => Promise<NextResponse>
) {
    return authenticateToken(async (req: AuthenticatedRequest, context?: T) => {
        console.log(`[Admin Access Check] User ID: ${req.user?.userId}, Role: ${req.user?.role}`);

        if (req.user?.role !== 'admin') {
            return NextResponse.json(
                { error: 'Admin access required' },
                { status: 403 }
            );
        }

        return handler(req, context);
    });
}
