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

const getList = async (
	userId,
	{ sortBy, sortByDesc, filter, limit = '500', page = '1', sub }
) => {
	const options = { owner: userId };
	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 getListById = async (companionId, userId) => {
	const messages = await Message.find({
		companionId,
		owner: userId,
	});
	return messages;
};

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

const getLastMessagesList = async (userId) => {
	const messages = await Message.find({ owner: userId });
	return messages;
};

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;
};

module.exports = {
	getList,
	getListById,
	getByField,
	getById,
	getLastMessagesList,
	add,
	remove,
};
