import {collection, getDocs, query, where, setDoc, doc, Firestore} from "firebase/firestore";
import {shuffle} from "lodash";
import {Exam, Variant} from "@/interfaces/exam";
import {Stat} from "@/interfaces/user";

export const getExams = async (
	db: Firestore,
	module: string,
	avoidRepeated: string,
	// added userId as due to assignments being set from the teacher to the student
	// we need to make sure we are serving exams not executed by the user and not
	// by the teacher that performed the request
	userId: string | undefined,
	variant?: Variant,
): Promise<Exam[]> => {
	const moduleRef = collection(db, module);

	const q = query(moduleRef, where("isDiagnostic", "==", false));
	const snapshot = await getDocs(q);

	const exams: Exam[] = filterByVariant(
		shuffle(
			snapshot.docs.map((doc) => ({
				id: doc.id,
				...doc.data(),
				module,
			})),
		) as Exam[],
		variant,
	);

	if (avoidRepeated === "true") {
		const statsQ = query(collection(db, "stats"), where("user", "==", userId));
		const statsSnapshot = await getDocs(statsQ);

		const stats: Stat[] = statsSnapshot.docs.map((doc) => ({
			id: doc.id,
			...doc.data(),
		})) as unknown as Stat[];
		const filteredExams = exams.filter((x) => !stats.map((s) => s.exam).includes(x.id));

		return filteredExams.length > 0 ? filteredExams : exams;
	}

	return exams;
};

const filterByVariant = (exams: Exam[], variant?: Variant) => {
	const filtered = variant && variant === "partial" ? exams.filter((x) => x.variant === "partial") : exams.filter((x) => x.variant !== "partial");
	return filtered.length > 0 ? filtered : exams;
};
