const ChatModel = require('../model/chat');
const UserModel = require('../model/user');

const listChats = async (req, res, next) => {
	try {
		const userId = req.user.id;
		const chats = await ChatModel.getList(userId, req.query);
		return res.json({
			status: 'success',
			code: 200,
			data: {
				...chats,
			},
		});
	} catch (e) {
		next(e);
	}
};

const startChat = async (req, res, next) => {
	try {
		const id = req.body.id;
		const user = req.user;
		const userId = user.id;
		const companion = await UserModel.findById(id);
		const isUser = await ChatModel.getByField(id, userId);
		const isCompanion = await ChatModel.getByField(userId, id);
		const { name, lastName, avatarUrl, color } = companion;
		const {
			name: Name,
			lastName: LastName,
			avatarUrl: AvatarUrl,
			color: Color,
		} = user;
		if ((companion && isUser) || isCompanion) {
			await ChatModel.update(isUser._id, { name, lastName, avatarUrl, color });
			await ChatModel.update(isCompanion._id, {
				name: Name,
				lastName: LastName,
				avatarUrl: AvatarUrl,
				color: Color,
			});
			return res.status(200).json({
				status: 'success',
				code: 200,
				data: companion,
			});
		}

		if (companion && !isUser && !isCompanion) {
			await ChatModel.add({
				name,
				lastName,
				avatarUrl,
				color,
				companionId: id,
				owner: userId,
			});
			await ChatModel.add({
				name: Name,
				lastName: LastName,
				avatarUrl: AvatarUrl,
				color: Color,
				companionId: userId,
				owner: id,
			});
			return res.status(201).json({
				status: 'success',
				code: 201,
				data: companion,
			});
		}
	} catch (e) {
		next(e);
	}
};

module.exports = {
	listChats,
	startChat,
};
