// updating specific user changes other users
// for example, updating the status of a corporate user should  update the status of all users in the same corporate group
import { UserStatus, User } from "../interfaces/user";
import client from "@/lib/mongodb";

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

export const propagateStatusChange = (userId: string, status: UserStatus) =>
	new Promise((resolve, reject) => {
		db.collection("users").findOne<User>({ id: userId })
			.then((docUser) => {
				if (!docUser) return;
				const user = docUser;

				// only update the status of the user's groups if the user is a corporate user
				if (user.type === "corporate" || user.type === "mastercorporate") {
					db.collection("groups").find({ admin: userId }).toArray().then(async (userGroupsRef) => {
						const userGroups = userGroupsRef.map((x) => x.data());

						const targetUsers = [...new Set(userGroups.flatMap((g) => g.participants).filter((u) => u))];

						Promise.all(
							targetUsers.map(async (targetUserId) => {
								const ref = await db.collection("users").findOne<User>({ id: targetUserId });
								if (!ref) return null;
								return ref;
							}),
						)
							.then((data) => {
								const filtered = data.filter((x) => {
									if (x === null) return false;
									if (x.status === status) return false;
									return true;
								}) as User[];

								if (filtered.length === 0) {
									return;
								}

								Promise.all(filtered.map((user: User) => db.collection("users").updateOne({ id: user.id }, { $set: { status } })))
									.then(() => {
										resolve(true);
									})
									.catch((err) => {
										console.error(err);
										reject(err);
									});
							})
							.catch((err) => {
								console.error(err);
								reject(err);
							});
					});
					return;
				}

				const error = new Error("User is not a corporate user");
				console.error(error);
				reject(error);
			})
			.catch((err) => {
				console.error(err);
				reject(err);
			});
	});

export const propagateExpiryDateChanges = (userId: string, initialExpiryDate: Date | null | undefined, subscriptionExpirationDate: Date | null) =>
	new Promise((resolve, reject) => {
		db.collection("users").findOne<User>({ id: userId })
			.then((user) => {
				if (!user) return;

				// only update the status of the user's groups if the user is a corporate user
				if (user.type === "corporate") {
					db.collection("groups").find({ admin: userId }).toArray().then(async (userGroupsRef) => {
						const userGroups = userGroupsRef.map((x) => x.data());

						const targetUsers = [...new Set(userGroups.flatMap((g) => g.participants).filter((u) => u))];

						Promise.all(
							targetUsers.map(async (targetUserId) => {
								const ref = await db.collection("users").findOne<User>({ id: targetUserId });
								return ref;
							}),
						)
							.then(async (data) => {
								const filtered = data.filter((x) => {
									if (x === null) return false;
									if (!x.subscriptionExpirationDate && !initialExpiryDate) return true;
									if (x.subscriptionExpirationDate !== initialExpiryDate) return false;
									return true;
								}) as User[];

								if (filtered.length === 0) return;

								for (const user of filtered) {
									await db.collection("users").updateOne(
										{ id: user.id },
										{ $set: { subscriptionExpirationDate } }
									);
								}

								resolve(true);
							})
							.catch((err) => {
								console.error(err);
								reject(err);
							});
					});
					return;
				}

				const error = new Error("User is not a corporate user");
				console.error(error);
				reject(error);
			})
			.catch((err) => {
				console.error(err);
				reject(err);
			});
	});
