import { ensureArrayQueryFilter } from "../ensureArrayQueryFilter.mjs";
import { getFiltersAndPaginationFromBody } from "./getFiltersAndPaginationFromBody.mjs";

//#region src/utils/filtersAndPagination/getDiscussionFiltersAndPagination.ts
/**
* Extracts filters and pagination information for discussions.
* Enforces that non-admin users can only see their own discussions.
*/
const getDiscussionFiltersAndPagination = (req, res) => {
	const { filters: filtersRequest, ...pagination } = getFiltersAndPaginationFromBody(req);
	const { roles, user } = res.locals;
	let filters = {};
	let sortOptions = { updatedAt: -1 };
	const { ids, userId, userIds, discussionId, search, isArchived, sortBy, sortOrder, fetchAll } = filtersRequest ?? {};
	if (ids) filters = {
		...filters,
		_id: { $in: ensureArrayQueryFilter(ids) }
	};
	if (discussionId) filters = {
		...filters,
		discussionId
	};
	if (typeof isArchived !== "undefined") filters = {
		...filters,
		isArchived: isArchived === "true"
	};
	if (userId) filters = {
		...filters,
		userId
	};
	if (userIds) filters = {
		...filters,
		userId: { $in: ensureArrayQueryFilter(userIds) }
	};
	if (search) {
		const searchRegex = new RegExp(search, "i");
		filters = {
			...filters,
			$or: [
				{ discussionId: searchRegex },
				{ title: searchRegex },
				{ "messages.content": searchRegex }
			]
		};
	}
	if (sortBy && sortOrder && (sortOrder === "asc" || sortOrder === "desc")) sortOptions = { [sortBy]: sortOrder === "asc" ? 1 : -1 };
	const isAdmin = roles.includes("admin");
	if (!isAdmin && user?.id) filters = {
		...filters,
		userId: user.id
	};
	else if (isAdmin && fetchAll !== "true" && user?.id) filters = {
		...filters,
		userId: user.id
	};
	return {
		filters,
		sortOptions,
		...pagination
	};
};

//#endregion
export { getDiscussionFiltersAndPagination };
//# sourceMappingURL=getDiscussionFiltersAndPagination.mjs.map