const ContactModel = require('../model/contact');
const UserModel = require('../model/user');
const ChatModel = require('../model/chat');
const MessageModel = require('../model/message');

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

const getContactById = async (req, res, next) => {
	try {
		const id = req.params.id;
		const userId = req.user.id;
		const contact = await ContactModel.getById(id, userId);
		if (contact)
			return res.json({
				status: 'success',
				code: 200,
				data: {
					contact,
				},
			});
		return res.status(404).json({
			status: 'error',
			code: 404,
			data: 'Not Found',
		});
	} catch (e) {
		next(e);
	}
};

const addContact = async (req, res, next) => {
	try {
		const userId = req.user.id;
		const userNumber = req.user.number;
		const number = req.body.number;
		const user = await UserModel.findByNumber(number);
		const isExist = await ContactModel.getByField(number, userId);
		if (user && userNumber !== number && !isExist) {
			const { name, lastName, country, avatarUrl, color, _id } = user;
			const newContact = await ContactModel.add({
				companionId: _id,
				name,
				lastName,
				number,
				country,
				avatarUrl,
				color,
				owner: userId,
			});
			return res.status(201).json({
				status: 'success',
				code: 201,
				data: newContact,
			});
		}
		return res.status(404).json({
			status: 'error',
			code: 404,
			data: 'Not Found',
		});
	} catch (e) {
		next(e);
	}
};

const updateContact = async (req, res, next) => {
	try {
		const { id, _id, name, lastName, companionId } = req.body;
		const userId = req.user.id;
		await ContactModel.update(id, userId, { name, lastName });
		await ChatModel.update(_id, userId, { name, lastName });
		await MessageModel.updateOwnerMessages(
			{ companionId, companionIdFlow: { $ne: userId }, owner: userId },
			{ name, lastName }
		);
		return res.status(200).json({
			data: {},
		});
	} catch (e) {
		next(e);
	}
};

const removeContact = async (req, res, next) => {
	try {
		const id = req.params.id;
		const userId = req.user.id;
		const contact = await ContactModel.remove(id, userId);
		if (contact) {
			return res.json({
				status: 'success',
				code: 200,
				data: {
					contact,
				},
			});
		} else {
			return res.status(404).json({
				status: 'error',
				code: 404,
				data: 'Not Found',
			});
		}
	} catch (e) {
		next(e);
	}
};

module.exports = {
	listContacts,
	getContactById,
	addContact,
	removeContact,
	updateContact,
};
