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

//#region src/utils/filtersAndPagination/getOrganizationFiltersAndPagination.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 getOrganizationFiltersAndPagination = (req, res) => {
	const { filters: filtersRequest, ...pagination } = getFiltersAndPaginationFromBody(req);
	const { roles, user } = res.locals;
	let filters = {};
	let sortOptions = { updatedAt: -1 };
	const { name, search, ids, membersIds, fetchAll, sortBy, sortOrder } = filtersRequest ?? {};
	if (ids) filters = {
		...filters,
		_id: { $in: ensureArrayQueryFilter(ids) }
	};
	if (!(roles.includes("admin") && fetchAll === "true")) filters = {
		...filters,
		membersIds: { $in: [user?.id] }
	};
	if (name) filters = {
		...filters,
		name: new RegExp(name, "i")
	};
	if (search) {
		const searchRegex = new RegExp(search, "i");
		filters = {
			...filters,
			$or: [{ name: searchRegex }]
		};
	}
	if (membersIds) filters = {
		...filters,
		membersIds: { $in: ensureArrayQueryFilter(membersIds) }
	};
	if (sortBy && sortOrder && (sortOrder === "asc" || sortOrder === "desc")) sortOptions = { [sortBy]: sortOrder === "asc" ? 1 : -1 };
	return {
		filters,
		sortOptions,
		...pagination
	};
};

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