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

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

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