import { db } from "./db";

export async function middleware(handler) {
    return async (req, res) => {
        const sessionId = req.cookies.session;
        if (!sessionId) {
            return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
        }

        const [rows] = await (await db).query('SELECT * FROM sessions WHERE SESSION_ID = ?', [sessionId]);
        if (rows.length === 0) {
            return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
        }

        req.user = rows[0].USER_ID;
        return handler(req);
    };
}