let validationError = require('../lib/errors/validationError.js');
let { User, Sequelize } = require('../models');
let bcrypt = require('bcryptjs');

exports.create = async function (username , password) {
	let user = await User.create({ username, hash: password });
	let userJson = user.toJSON();
	delete userJson.hash;

	return userJson;
};

exports.get = async function (userId) {
	let user = await User.findByPk(userId, {
		attributes: { exclude: ['hash'] }
	});

	if(user) {
		return user.toJSON();
	} else {
		throw validationError({
			message: 'User does not exist',
			value: userId
		});
	}
}

exports.getAllBeginningWith = async function (username) {
	let users = await User.findAll({
		attributes: { exclude: ['hash'] },
		where: {
			username: {
				[Sequelize.Op.like]: username + '%'
			}
		},
		limit: 10
	});

	let sorted = users.sort((a, b) => {
		if(a.username.length !== b.username.length) {
			return a.username.length > b.username.length
		} else {
			return a.username.localeCompare(b.username);
		}
	});

	return sorted.map(user => user.toJSON());
}

exports.login = async function (username, password) {
	let user = await User.findByPk({
		where: { username }
	});

	if(!user) {
		throw validationError({
			message: 'Username is incorrect',
			path: 'username',
			value: username
		});
	} else {
		let res = await bcrypt.compare(password, user.hash);

		if(res) {
			let userJson = user.toJSON();
			delete userJson.hash;
			return userJson;
		} else {
			throw validationError({
				message: 'Password is incorrect',
				path: 'hash',
				value: password
			});
		}
	}
};
