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

//#region src/utils/filtersAndPagination/getDictionaryFiltersAndPagination.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 getDictionaryFiltersAndPagination = (req, res) => {
	const { filters: filtersRequest, ...pagination } = getFiltersAndPaginationFromBody(req);
	const { roles, project } = res.locals;
	let filters = {};
	let sortOptions = { updatedAt: -1 };
	const { key, search, keys, tags, ids, projectId, projectIds, userId, userIds, creatorId, creatorIds, title, description, version, sortBy, sortOrder, fetchAll } = filtersRequest ?? {};
	if (ids) filters = {
		...filters,
		_id: { $in: ensureArrayQueryFilter(ids) }
	};
	if (projectId) filters = {
		...filters,
		projectIds: projectId
	};
	if (projectIds) filters = {
		...filters,
		projectIds: { $in: ensureArrayQueryFilter(projectIds) }
	};
	if (!(roles.includes("admin") && fetchAll === "true")) filters = {
		...filters,
		projectIds: { $in: project?.id }
	};
	if (userId) filters = {
		...filters,
		creatorId: userId
	};
	if (userIds) filters = {
		...filters,
		creatorId: { $in: ensureArrayQueryFilter(userIds) }
	};
	if (creatorId) filters = {
		...filters,
		creatorId
	};
	if (creatorIds) filters = {
		...filters,
		creatorId: { $in: ensureArrayQueryFilter(creatorIds) }
	};
	if (title) filters = {
		...filters,
		title: new RegExp(title, "i")
	};
	if (description) filters = {
		...filters,
		description: new RegExp(description, "i")
	};
	if (key) filters = {
		...filters,
		key: new RegExp(key, "i")
	};
	if (search) {
		const searchRegex = new RegExp(search, "i");
		filters = {
			...filters,
			$or: [
				{ key: searchRegex },
				{ title: searchRegex },
				{ description: searchRegex },
				{ tags: { $in: [searchRegex] } }
			]
		};
	}
	if (keys) filters = {
		...filters,
		key: { $in: ensureArrayQueryFilter(keys) }
	};
	if (tags) filters = {
		...filters,
		tags: { $in: ensureArrayQueryFilter(tags) }
	};
	if (version) filters = {
		...filters,
		content: { [version]: `$content.${version}` }
	};
	if (sortBy && sortOrder && (sortOrder === "asc" || sortOrder === "desc")) sortOptions = { [sortBy]: sortOrder === "asc" ? 1 : -1 };
	return {
		filters,
		sortOptions,
		...pagination
	};
};

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