import { Types } from 'mongoose'
import { User } from '../api/users/models'
import { CommunityMember } from '../api/community-members/models'

/*
Concordia - 6940fb887695b40bdcd6046c
McGill - 6940fb887695b40bdcd6053c
MIT - 6940fb887695b40bdcd6043f
*/

/**
 * Sync community-members for a given community.
 *
 * For the given communityId:
 * - Find all users where `communities` contains that communityId.
 * - Find existing `community-members` documents for that community.
 * - Insert missing `CommunityMember` docs (community + user) for users
 *   that are in `users.communities` but not yet in `community-members`.
 *
 * Usage (after build): node dist/src/scripts/sync-community-members.js <communityId>
 */
async function execute(communityIdStr: string = '6940fb887695b40bdcd6043f') {
	const communityId = new Types.ObjectId(communityIdStr)

	console.log('Syncing community-members for community:', communityIdStr)

	const [users, existingMembers] = await Promise.all([
		User.find({ communities: communityId }, { _id: 1 }).lean(),
		CommunityMember.find({ community: communityId }, { user: 1 }).lean(),
	])

	const existingUserIds = new Set(existingMembers.map((m: any) => String(m.user)))

	const docsToInsert = users
		.filter((u: any) => !existingUserIds.has(String(u._id)))
		.map((u: any) => ({
			community: communityId,
			user: u._id,
		}))

	if (!docsToInsert.length) {
		console.log('No missing community-members. Everything is up to date.')
		return
	}

	const result = await CommunityMember.insertMany(docsToInsert)
	console.log(`Inserted ${result.length} community-members for community ${communityIdStr}`)
}

const scriptSyncCommunityMembers = {
	execute,
}

export default scriptSyncCommunityMembers

