import { Router, Response } from "express";
import * as bodyparser from "body-parser";

import { authRoute } from "../security/token";

import { LRequest } from "../types/express";

const levelRouter = Router();
levelRouter.use(bodyparser.json());
levelRouter.use(authRoute);

levelRouter.get("/:id/vocab", async (req: LRequest, res: Response) => {
    if (!req.params || !req.params.id) {
        res.send({
            error: "400",
            data: {
                msg: "No level specified",
            },
        });
        return;
    }

    const levelId = parseInt(req.params.id);
    if (levelId === NaN) {
        res.send({
            error: "400",
            data: {
                msg: "Invalid level id",
            },
        });
        return;
    }

    // Find the level
    const { db } = req;
    const level = await db.collection("levels").findOne({
        level: levelId,
    });
    if (!level) {
        res.send({
            error: "404",
            data: {
                msg: `Cannot find level with id "${levelId}"`,
            },
        });
        return;
    }

    // Fetch all the vocabulary
    const vocab = await db.collection("vocabulary").find({ id: { $in: level.vocab } }).toArray();
    res.send({
        error: "0",
        data: {
            vocab,
        }
    });
});

export default levelRouter;
