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

//#region src/utils/filtersAndPagination/getUserFiltersAndPagination.ts
/**
* Extracts filters and pagination information from the request body.
* @param req - Express request object.
* @returns Object containing filters, page, pageSize, and getNumberOfPages functions.
*/
const getUserFiltersAndPagination = (req, res) => {
	const { filters: filtersRequest, ...pagination } = getFiltersAndPaginationFromBody(req);
	const { roles, organization } = res.locals;
	let filters = {};
	let sortOptions = { updatedAt: -1 };
	const { firstName, lastName, email, emailVerified, role, search, sortBy, sortOrder, ids, fetchAll } = filtersRequest ?? {};
	if (ids) {
		filters = {
			...filters,
			_id: { $in: ensureArrayQueryFilter(ids) }
		};
		if (!(roles.includes("admin") && fetchAll === "true")) {
			const secureMembersIds = ensureArrayQueryFilter(ids)?.filter((id) => organization?.membersIds?.map(String).includes(id)) ?? [];
			filters = {
				...filters,
				_id: { $in: secureMembersIds }
			};
		}
	}
	if (firstName) filters = {
		...filters,
		firstName: new RegExp(firstName, "i")
	};
	if (lastName) filters = {
		...filters,
		lastName: new RegExp(lastName, "i")
	};
	if (email) filters = {
		...filters,
		email: new RegExp(email, "i")
	};
	if (emailVerified !== void 0) {
		const isVerified = emailVerified === "true";
		filters = {
			...filters,
			emailVerified: isVerified
		};
	}
	if (role) filters = {
		...filters,
		role
	};
	if (search) {
		const searchRegex = new RegExp(search, "i");
		filters = {
			...filters,
			$or: [
				{ firstName: searchRegex },
				{ lastName: searchRegex },
				{ email: searchRegex },
				{ name: searchRegex }
			]
		};
	}
	if (sortBy && sortOrder && (sortOrder === "asc" || sortOrder === "desc")) sortOptions = { [sortBy]: sortOrder === "asc" ? 1 : -1 };
	return {
		filters,
		sortOptions,
		...pagination
	};
};

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