import type {NextApiRequest, NextApiResponse} from "next";
import client from "@/lib/mongodb";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";

const db = client.db(process.env.MONGODB_DB);

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (req.method === "GET") return get(req, res);
}

async function get(req: NextApiRequest, res: NextApiResponse) {
    if (!req.session.user) {
        res.status(401).json({ok: false});
        return;
    }

    const {sessionId, userId, exerciseIds} = req.query;
    const exercises = (exerciseIds! as string).split(',');
    const finishedEvaluations = await db.collection("evaluation").find({ 
        session_id: sessionId, 
        user: userId, 
        $or: [
            { status: "completed" },
            { status: "error" }
        ],
        exercise_id: { $in: exercises }
    }).toArray();

    const finishedExerciseIds = finishedEvaluations.map(evaluation => evaluation.exercise_id);
    res.status(200).json({ finishedExerciseIds });
}