// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {getFirestore, doc, getDoc, setDoc} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import axios, {AxiosResponse} from "axios";
import {app} from "@/firebase";
import {Stat} from "@/interfaces/user";
import {writingReverseMarking} from "@/utils/score";

interface Body {
	question: string;
	answer: string;
	id: string;
}

const db = getFirestore(app);
export default withIronSessionApiRoute(handler, sessionOptions);

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

	res.status(200).json(null);

	console.log("🌱 - Still processing");
	const backendRequest = await evaluate(req.body as Body);
	console.log("🌱 - Process complete");

	const correspondingStat = (await getDoc(doc(db, "stats", req.body.id))).data() as Stat;
	const solutions = correspondingStat.solutions.map((x) => ({...x, evaluation: backendRequest.data}));
	await setDoc(
		doc(db, "stats", (req.body as Body).id),
		{
			solutions,
			score: {
				correct: writingReverseMarking[backendRequest.data.overall],
				total: 100,
				missing: 0,
			},
		},
		{merge: true},
	);
	console.log("🌱 - Updated the DB");
}

async function evaluate(body: Body): Promise<AxiosResponse> {
	const backendRequest = await axios.post(`${process.env.BACKEND_URL}/writing_task2`, body as Body, {
		headers: {
			Authorization: `Bearer ${process.env.BACKEND_JWT}`,
		},
	});

	if (typeof backendRequest.data === "string") return evaluate(body);
	return backendRequest;
}
