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

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 getAssignmentsByAssignee = async (id: string, filter?: {[key in keyof Partial<Assignment>]: any}) => {
	return await db
		.collection("assignments")
		.find<Assignment>({assignees: [id], ...(!filter ? {} : filter)})
		.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 db
		.collection("assignments")
		.find<Assignment>({
			assigner: {$in: ids},
			...(!!startDate ? {startDate: {$gte: startDate.toISOString()}} : {}),
			...(!!endDate ? {endDate: {$lte: endDate.toISOString()}} : {}),
		})
		.toArray();
};

export const getEntityAssignments = async (id: string) => {
	return await db.collection("assignments").find<Assignment>({entity: id}).toArray();
};

export const getEntitiesAssignments = async (ids: string[]) => {
	return await db
		.collection("assignments")
		.find<Assignment>({entity: {$in: ids}})
		.toArray();
};

export const getAssignmentsForCorporates = async (userType: Type, idsList: string[], startDate?: Date, endDate?: Date) => {
	const assigners = await Promise.all(
		idsList.map(async (id) => {
			const assigners = await getAllAssignersByCorporate(id, userType);
			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();
};
