import { Brackets, SelectQueryBuilder } from "typeorm";
import type { User } from "@/models/entities/user.js";

type Viewer = Pick<User, "id"> & Partial<Pick<User, "minorBadges" | "isAdmin" | "isModerator">>;

export function shouldHideEUsersFor(viewer?: Viewer | null): boolean {
	return !!viewer &&
		!viewer.isAdmin &&
		!viewer.isModerator &&
		(viewer.minorBadges ?? []).some((badge) => badge === "K" || badge === "T");
}

export function generateMinorBadgeUserVisibilityQuery(
	q: SelectQueryBuilder<any>,
	viewer?: Viewer | null,
	alias = "user",
) {
	if (!shouldHideEUsersFor(viewer)) return;

	q.andWhere(
		new Brackets((qb) => {
			qb
				.where(`${alias}.id = :minorBadgeViewerId`)
				.orWhere(`NOT ('E' = ANY(${alias}."minorBadges"))`);
		}),
	);
	q.setParameter("minorBadgeViewerId", viewer!.id);
}

export function generateMinorBadgeNoteVisibilityQuery(
	q: SelectQueryBuilder<any>,
	viewer?: Viewer | null,
	noteAlias = "note",
) {
	if (!shouldHideEUsersFor(viewer)) return;

	q.andWhere(
		new Brackets((qb) => {
			qb
				.where(`${noteAlias}."userId" = :minorBadgeViewerId`)
				.orWhere(
					`${noteAlias}."userId" NOT IN (` +
						`SELECT "id" FROM "user" WHERE 'E' = ANY("minorBadges")` +
					`)`,
				);
		}),
	);
	q.setParameter("minorBadgeViewerId", viewer!.id);
}
