const ContactModel = require('../model/contact');
const UserModel = require('../model/user');

const listContacts = async (req, res, next) => {
	try {
		const userId = req.user.id;
		const contacts = await ContactModel.getList(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 number = req.body.number;
		const user = await UserModel.findByNumber(number);
		const isExist = await ContactModel.getByField(number, userId);
		if (user && !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 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);
	}
};

const updateContact = async (req, res, next) => {
	try {
		const id = req.params.id;
		const userId = req.user.id;
		const contact = await ContactModel.update(id, userId, req.body);
		if (contact) {
			return res.status(200).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,
};
