const Message = require('./schemas/message');

const getList = async (
	options,
	{ sortBy, sortByDesc, filter, limit = '500', page = '1', sub }
) => {
	if (sub) options.subscription = { $all: [sub] };
	const results = await Message.paginate(options, {
		limit,
		page,
		sort: {
			...(sortBy ? { [`${sortBy}`]: 1 } : {}),
			...(sortByDesc ? { [`${sortByDesc}`]: -1 } : {}),
		},
		select: filter ? filter.split('|').join(' ') : '',
		populate: {
			path: 'owner',
			select: '_id',
		},
	});
	const { docs: messages, totalDocs: total } = results;
	return { total: total.toString(), limit, page, messages };
};

const getById = async (id, userId) => {
	const foundMessage = await Message.findById({
		_id: id,
		owner: userId,
	});
	return foundMessage;
};

const getByField = async (number, userId) => {
	const message = await Message.findOne({
		number,
		owner: userId,
	});
	return message;
};

const add = async (obj) => {
	const message = await Message.create(obj);
	return message;
};

const remove = async (id, userId) => {
	const removedMessage = await Message.findByIdAndRemove({
		_id: id,
		owner: userId,
	});
	return removedMessage;
};

const removeByFields = async (companionId, idTime, userId) => {
	const removedMessage = await Message.findOne({
		companionId,
		idTime,
		owner: userId,
	}).deleteOne();
	return removedMessage;
};

const removeAll = async (companionId, userId) => {
	const removedAllMessages = await Message.deleteMany({
		companionId,
		owner: userId,
	});
	return removedAllMessages;
};

const updateCompanionsMessages = async (companionId, obj) => {
	const messages = await Message.updateMany({ companionId }, { ...obj });
	return messages;
};

const updateOwnerMessages = async (options, obj) => {
	const messages = await Message.updateMany({ ...options }, { ...obj });
	return messages;
};

module.exports = {
	getList,
	getByField,
	getById,
	add,
	remove,
	removeByFields,
	removeAll,
	updateCompanionsMessages,
	updateOwnerMessages,
};
