import type { LoaderFunctionArgs } from "react-router";
import * as R from "remeda";
import * as AssociationsRepository from "~/features/associations/AssociationRepository.server";
import * as Association from "~/features/associations/core/Association";
import { getUser } from "~/features/auth/core/user.server";
import * as UserCardRepository from "~/features/user-card/UserCardRepository.server";
import { parseSearchParams } from "~/utils/remix.server";
import * as TeamRepository from "../../team/TeamRepository.server";
import * as Scrim from "../core/Scrim";
import * as ScrimPostRepository from "../ScrimPostRepository.server";
import { scrimsFiltersSearchParamsObject } from "../scrims-schemas";
import { dividePosts } from "../scrims-utils";

export const loader = async ({ request }: LoaderFunctionArgs) => {
	const user = getUser();

	const associations = user
		? await AssociationsRepository.findByMemberUserId(user?.id)
		: null;

	const filtersFromSearchParams = parseSearchParams({
		request,
		schema: scrimsFiltersSearchParamsObject,
	}).filters;

	const filters = Scrim.filtersAreDefault(filtersFromSearchParams)
		? user?.preferences?.defaultScrimsFilters
		: filtersFromSearchParams;

	const posts = (await ScrimPostRepository.findAllRelevant())
		.filter(
			(post) =>
				(user && Scrim.isParticipating(post, user.id)) ||
				Association.isVisible({
					associations,
					visibility: post.visibility,
					contentOwnerUserId: post.users.find((u) => u.isOwner)?.id,
				}),
		)
		.map((post) => ({
			...post,
			visibility: null,
			isPrivate: !Association.isPublic({
				visibility: post.visibility,
			}),
		}));

	const cardUserIds = R.unique(
		posts.flatMap((post) => [
			...post.users.map((user) => user.id),
			...post.requests.flatMap((request) =>
				request.users.map((user) => user.id),
			),
		]),
	);

	return {
		...(await UserCardRepository.userCards({
			userIds: cardUserIds,
		})),
		posts: dividePosts(posts, user?.id),
		teams: user ? await TeamRepository.teamsByMemberUserId(user.id) : [],
		filters: filters ?? Scrim.defaultFilters(),
	};
};
