import {collection, doc, getDoc, getDocs, getFirestore, query, setDoc, where} from "firebase/firestore";
import {app} from "@/firebase";
import {Group, Type, User} from "@/interfaces/user";
import {uuidv4} from "@firebase/util";

const db = getFirestore(app);

export const addUserToGroupOnCreation = async (userId: string, type: Type, creatorId: string) => {
	const creatorDoc = await getDoc(doc(db, "users", creatorId));
	if (!creatorDoc.exists()) return false;

	const creator = {...creatorDoc.data(), id: creatorDoc.id} as User;

	const creatorGroupsDocs = await getDocs(query(collection(db, "groups"), where("admin", "==", creator.id)));
	const typeGroup = creatorGroupsDocs.docs.find((x) => (x.data() as Group).name === (type === "student" ? "Students" : "Teachers"));

	if (typeGroup && typeGroup.exists()) {
		await setDoc(typeGroup.ref, {participants: [...typeGroup.data().participants, userId]}, {merge: true});
		return true;
	}

	const groupId = uuidv4();
	await setDoc(doc(db, "groups", groupId), {
		admin: creatorId,
		name: type === "student" ? "Students" : "Teachers",
		id: groupId,
		participants: [userId],
		disableEditing: true,
	} as Group);
	return true;
};
