import client from "@/lib/mongodb";
import { Assignment } from "@/interfaces/results";
import { getAllAssignersByCorporate } from "@/utils/groups.be";

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

export const getAssignmentsByAssigner = async (id: string, startDate?: Date, endDate?: Date) => {
	let query: any = { assigner: id };

	if (startDate) {
		query.startDate = { $gte: startDate.toISOString() };
	}

	if (endDate) {
		query.endDate = { $lte: endDate.toISOString() };
	}

	return await db.collection("assignments").find<Assignment>(query).toArray();
};
export const getAssignments = async () => {
	return await db.collection("assignments").find<Assignment>({}).toArray();
};

export const getAssignmentsByAssignerBetweenDates = async (id: string, startDate: Date, endDate: Date) => {
	return await db.collection("assignments").find<Assignment>({assigner: id}).toArray();
};

export const getAssignmentsByAssigners = async (ids: string[], startDate?: Date, endDate?: Date) => {
	return (await Promise.all(ids.map((id) => getAssignmentsByAssigner(id, startDate, endDate)))).flat();
};

export const getAssignmentsForCorporates = async (idsList: string[], startDate?: Date, endDate?: Date) => {
	const assigners = await Promise.all(
		idsList.map(async (id) => {
			const assigners = await getAllAssignersByCorporate(id);
			return {
				corporateId: id,
				assigners,
			};
		}),
	);

	const assignments = await Promise.all(
		assigners.map(async (data) => {
			try {
				const assigners = [...new Set([...data.assigners, data.corporateId])];
				const assignments = await getAssignmentsByAssigners(assigners, startDate, endDate);
				return assignments.map((assignment) => ({
					...assignment,
					corporateId: data.corporateId,
				}));
			} catch (err) {
				console.error(err);
				return [];
			}
		}),
	);

	return assignments.flat();
}