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

//#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 } = require_utils_filtersAndPagination_getFiltersAndPaginationFromBody.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: require_utils_ensureArrayQueryFilter.ensureArrayQueryFilter(ids) }
	};
	if (projectId) filters = {
		...filters,
		projectIds: projectId
	};
	if (projectIds) filters = {
		...filters,
		projectIds: { $in: require_utils_ensureArrayQueryFilter.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: require_utils_ensureArrayQueryFilter.ensureArrayQueryFilter(userIds) }
	};
	if (creatorId) filters = {
		...filters,
		creatorId
	};
	if (creatorIds) filters = {
		...filters,
		creatorId: { $in: require_utils_ensureArrayQueryFilter.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: require_utils_ensureArrayQueryFilter.ensureArrayQueryFilter(keys) }
	};
	if (tags) filters = {
		...filters,
		tags: { $in: require_utils_ensureArrayQueryFilter.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
exports.getDictionaryFiltersAndPagination = getDictionaryFiltersAndPagination;
//# sourceMappingURL=getDictionaryFiltersAndPagination.cjs.map