const require_utils_ensureArrayQueryFilter = require('../ensureArrayQueryFilter.cjs');
const require_utils_filtersAndPagination_getFiltersAndPaginationFromBody = require('./getFiltersAndPaginationFromBody.cjs');

//#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 } = require_utils_filtersAndPagination_getFiltersAndPaginationFromBody.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: require_utils_ensureArrayQueryFilter.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: require_utils_ensureArrayQueryFilter.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
exports.getDiscussionFiltersAndPagination = getDiscussionFiltersAndPagination;
//# sourceMappingURL=getDiscussionFiltersAndPagination.cjs.map