import { GenericError } from "../utils/errors/ErrorsClass.mjs";
import { validateTag } from "../utils/validation/validateTag.mjs";
import { TagModel } from "../models/tag.model.mjs";

//#region src/services/tag.service.ts
/**
* Finds tags based on filters and pagination options.
* @param filters - MongoDB filter query.
* @param skip - Number of documents to skip.
* @param limit - Number of documents to limit.
* @returns List of tags matching the filters.
*/
const findTags = async (filters, skip = 0, limit = 100, sortOptions) => {
	let query = TagModel.find(filters).skip(skip).limit(limit);
	if (sortOptions && Object.keys(sortOptions).length > 0) query = query.sort(sortOptions);
	return await query;
};
/**
* Finds a tag by its ID.
* @param tagId - The ID of the tag to find.
* @returns The tag matching the ID.
*/
const getTagById = async (tagId) => {
	const tag = await TagModel.findById(tagId);
	if (!tag) throw new GenericError("TAG_NOT_FOUND", { tagId });
	return tag;
};
const getTagsByKeys = async (keys, organizationId) => {
	return await TagModel.find({
		key: { $in: keys },
		organizationId
	});
};
/**
* Counts the total number of tags that match the filters.
* @param filters - MongoDB filter query.
* @returns Total number of tags.
*/
const countTags = async (filters) => {
	const result = await TagModel.countDocuments(filters);
	if (typeof result === "undefined") throw new GenericError("TAG_COUNT_FAILED", { filters });
	return result;
};
/**
* Creates a new tag in the database.
* @param  tag - The tag data to create.
* @returns The created tag.
*/
const createTag = async (tag) => {
	const errors = await validateTag(tag, ["key"]);
	if (Object.keys(errors).length > 0) throw new GenericError("TAG_INVALID_FIELDS", { errors });
	return await TagModel.create(tag);
};
/**
* Updates an existing tag in the database by its ID.
* @param tagId - The ID of the tag to update.
* @param tag - The updated tag data.
* @returns The updated tag.
*/
const updateTagById = async (tagId, tag) => {
	const errors = validateTag(tag, Object.keys(tag));
	if (Object.keys(errors).length > 0) throw new GenericError("TAG_INVALID_FIELDS", {
		tagId,
		errors
	});
	if ((await TagModel.updateOne({ _id: tagId }, tag)).matchedCount === 0) throw new GenericError("TAG_UPDATE_FAILED", { tagId });
	return await getTagById(tagId);
};
/**
* Deletes a tag from the database by its ID.
* @param tagId - The ID of the tag to delete.
* @returns The result of the deletion operation.
*/
const deleteTagById = async (tagId) => {
	const tag = await TagModel.findByIdAndDelete(tagId);
	if (!tag) throw new GenericError("TAG_NOT_FOUND", { tagId });
	return tag;
};

//#endregion
export { countTags, createTag, deleteTagById, findTags, getTagById, getTagsByKeys, updateTagById };
//# sourceMappingURL=tag.service.mjs.map