import {CEFR_STEPS} from "@/resources/grading";
import {getUserCorporate} from "@/utils/groups.be";
import {User} from "@/interfaces/user";
import {Grading} from "@/interfaces";
import client from "@/lib/mongodb";

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

export const getGradingSystem = async (user: User): Promise<Grading> => {
	const grading = await db.collection("grading").findOne<Grading>({id: user.id});
	if (!!grading) return grading;

	if (user.type !== "teacher" && user.type !== "student") return {steps: CEFR_STEPS, user: user.id};

	const corporate = await getUserCorporate(user.id);
	if (!corporate) return {steps: CEFR_STEPS, user: user.id};

	const corporateSnapshot = await db.collection("grading").findOne<Grading>({id: corporate.id});
	if (!!corporateSnapshot) return corporateSnapshot;

	return {steps: CEFR_STEPS, user: user.id};
};

export const getGradingSystemByEntity = async (id: string) =>
	(await db.collection("grading").findOne<Grading>({entity: id})) || {steps: CEFR_STEPS, user: ""};
