import * as R from "remeda";
import { getUser } from "~/features/auth/core/user.server";
import * as Seasons from "~/features/mmr/core/Seasons";
import type { TieredSkill } from "~/features/mmr/tiered.server";
import { userSkills } from "~/features/mmr/tiered.server";
import * as UserCardRepository from "~/features/user-card/UserCardRepository.server";
import type { Unpacked } from "~/utils/types";
import * as LFGRepository from "../LFGRepository.server";

export const loader = async () => {
	const user = getUser();
	const posts = await LFGRepository.posts(user);

	const cardUserIds = R.unique(
		posts.flatMap((post) => [
			post.author.id,
			...(post.team?.members ?? []).map((member) => member.id),
		]),
	);

	return {
		posts,
		tiersMap: postsUsersTiersMap(posts),
		...(await UserCardRepository.userCards({
			userIds: cardUserIds,
		})),
	};
};

function postsUsersTiersMap(
	posts: Unpacked<ReturnType<typeof LFGRepository.posts>>,
) {
	const latestSeason = Seasons.currentOrPrevious()!.nth;
	const previousSeason = latestSeason - 1;

	const latestSeasonSkills = userSkills(latestSeason).userSkills;
	const previousSeasonSkills = userSkills(previousSeason).userSkills;

	const uniqueUsers = new Set<number>();
	for (const post of posts) {
		uniqueUsers.add(post.author.id);

		for (const user of post.team?.members ?? []) {
			uniqueUsers.add(user.id);
		}
	}

	const userSkillsMap = new Map<
		number,
		{ latest?: TieredSkill["tier"]; previous?: TieredSkill["tier"] }
	>();

	for (const userId of uniqueUsers) {
		const tiers = {
			latest:
				latestSeasonSkills[userId] && !latestSeasonSkills[userId].approximate
					? latestSeasonSkills[userId].tier
					: undefined,
			previous:
				previousSeasonSkills[userId] &&
				!previousSeasonSkills[userId].approximate
					? previousSeasonSkills[userId].tier
					: undefined,
		};

		if (tiers.latest || tiers.previous) {
			userSkillsMap.set(userId, tiers);
		}
	}

	return Array.from(userSkillsMap.entries());
}
