import {app} from "@/firebase";
import {Assignment} from "@/interfaces/results";
import {CorporateUser, Group, GroupWithUsers, MasterCorporateUser, StudentUser, TeacherUser, Type, User} from "@/interfaces/user";
import client from "@/lib/mongodb";
import moment from "moment";
import {getLinkedUsers, getUser} from "./users.be";
import {getSpecificUsers} from "./users.be";

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

export const updateExpiryDateOnGroup = async (participantID: string, corporateID: string) => {
	const corporate = await db.collection("users").findOne<User>({id: corporateID});
	const participant = await db.collection("users").findOne<User>({id: participantID});

	if (!corporate || !participant) return;
	if (corporate.type !== "corporate" || (participant.type !== "student" && participant.type !== "teacher")) return;

	if (!corporate.subscriptionExpirationDate || !participant.subscriptionExpirationDate)
		return await db.collection("users").updateOne({id: participant.id}, {$set: {subscriptionExpirationDate: null}});

	const corporateDate = moment(corporate.subscriptionExpirationDate);
	const participantDate = moment(participant.subscriptionExpirationDate);

	if (corporateDate.isAfter(participantDate))
		return await db.collection("users").updateOne({id: participant.id}, {$set: {subscriptionExpirationDate: corporateDate.toISOString()}});

	return;
};

export const getUserCorporate = async (id: string) => {
	const user = await getUser(id);
	if (!user) return undefined;

	if (["admin", "developer"].includes(user.type)) return undefined;
	if (user.type === "mastercorporate") return user;

	const groups = await getParticipantGroups(id);
	const admins = await Promise.all(groups.map((x) => x.admin).map(getUser));
	const corporates = admins
		.filter((x) => (user.type === "corporate" ? x?.type === "mastercorporate" : x?.type === "corporate"))
		.filter((x) => !!x) as User[];

	if (corporates.length === 0) return undefined;
	return corporates.shift() as CorporateUser | MasterCorporateUser;
};

export const getGroup = async (id: string) => {
	return await db.collection("groups").findOne<Group>({id});
};

export const getGroups = async () => {
	return await db.collection("groups").find<Group>({}).toArray();
};

export const getParticipantGroups = async (id: string) => {
	return await db.collection("groups").find<Group>({participants: id}).toArray();
};

export const getUserGroups = async (id: string): Promise<Group[]> => {
	return await db.collection("groups").find<Group>({admin: id}).toArray();
};

export const getUserNamedGroup = async (id: string, name: string) => {
	return await db.collection("groups").findOne<Group>({admin: id, name});
};

export const getUsersGroups = async (ids: string[]) => {
	return await db
		.collection("groups")
		.find<Group>({admin: {$in: ids}})
		.toArray();
};

export const convertToUsers = (group: Group, users: User[]): GroupWithUsers =>
	Object.assign(group, {
		admin: users.find((u) => u.id === group.admin),
		participants: group.participants.map((p) => users.find((u) => u.id === p)).filter((x) => !!x) as User[],
	});

export const getAllAssignersByCorporate = async (corporateID: string, type: Type): Promise<string[]> => {
	const linkedTeachers = await getLinkedUsers(corporateID, type, "teacher");
	const linkedCorporates = await getLinkedUsers(corporateID, type, "corporate");

	return [...linkedTeachers.users.map((x) => x.id), ...linkedCorporates.users.map((x) => x.id)];
};

export const getGroupsForUser = async (admin?: string, participant?: string) => {
	if (admin && participant) return await db.collection("groups").find<Group>({admin, participant}).toArray();

	if (admin) return await getUserGroups(admin);
	if (participant) return await getParticipantGroups(participant);

	return await getGroups();
};

export const getStudentGroupsForUsersWithoutAdmin = async (admin: string, participants: string[]) => {
	return await db
		.collection("groups")
		.find<Group>({...(admin ? {admin: {$ne: admin}} : {}), ...(participants ? {participants} : {})})
		.toArray();
};

export const getCorporateNameForStudent = async (studentID: string) => {
	const groups = await getStudentGroupsForUsersWithoutAdmin("", [studentID]);
	if (groups.length === 0) return "";

	const adminUserIds = [...new Set(groups.map((g) => g.admin))];
	const adminUsersData = (await getSpecificUsers(adminUserIds)).filter((x) => !!x) as User[];

	if (adminUsersData.length === 0) return "";
	const admins = adminUsersData.filter((x) => x.type === "corporate");

	if (admins.length > 0) {
		return (admins[0] as CorporateUser).corporateInformation.companyInformation.name;
	}

	return "";
};

export const getGroupsByEntity = async (id: string) => await db.collection("groups").find<Group>({entity: id}).toArray();

export const getGroupsByEntities = async (ids: string[]) =>
	await db
		.collection("groups")
		.find<Group>({entity: {$in: ids}})
		.toArray();
