import type { NextApiRequest, NextApiResponse } from "next";
import client from "@/lib/mongodb";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { UserSolution } from "@/interfaces/exam";
import { speakingReverseMarking, writingReverseMarking } from "@/utils/score";

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

export default withIronSessionApiRoute(handler, sessionOptions);

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

async function post(req: NextApiRequest, res: NextApiResponse) {
    if (!req.session.user) {
        res.status(401).json({ ok: false });
        return;
    }
    const { sessionId, userId, userSolutions } = req.body;
    const completedEvals = await db.collection("evaluation").find({
        session_id: sessionId,
        user: userId,
        status: "completed"
    }).toArray();

    const evalsByExercise = new Map(
        completedEvals.map(e => [e.exercise_id, e])
    );

    const solutionsWithEvals = userSolutions.filter((solution: UserSolution) =>
        evalsByExercise.has(solution.exercise)
    ).map((solution: any) => {
        const evaluation = evalsByExercise.get(solution.exercise)!;

        if (solution.type === 'writing') {
            return {
                ...solution,
                solutions: [{
                    ...solution.solutions[0],
                    evaluation: evaluation.result
                }],
                score: {
                    correct: writingReverseMarking[evaluation.result.overall],
                    total: 100,
                    missing: 0
                },
                isDisabled: false
            };
        }

        if (solution.type === 'speaking' || solution.type === 'interactiveSpeaking') {
            return {
                ...solution,
                solutions: [{
                    ...solution.solutions[0],
                    ...(
                        solution.type === 'speaking'
                            ? { fullPath: evaluation.result.fullPath }
                            : { answer: evaluation.result.answer }
                    ),
                    evaluation: evaluation.result
                }],
                score: {
                    correct: speakingReverseMarking[evaluation.result.overall || 0] || 0,
                    total: 100,
                    missing: 0
                },
                isDisabled: false
            };
        }
        return {
            solution,
            evaluation
        };
    });

    res.status(200).json(solutionsWithEvals)
}
