const { pool } = require('../connection');

const IPUser = Symbol("IPUser");
const HostUser = Symbol("HostUser");
const NamedUser = Symbol("NamedUser");

async function userOfType(type, opts = {}) {
	opts = {active: true, ...opts};

	let propertyName;
	switch (type) {
		case IPUser:
			propertyName = "ip";
			break;
		case HostUser:
			propertyName = "host";
			break;
		case NamedUser:
			propertyName = "hash";
			break;
	}

	if (propertyName) {

		const text = `
			SELECT *
			FROM keystore
			WHERE type = 'user' AND data ? $1
		`;

		const res = await pool.query(text, [ propertyName ]);

		const users = res.rows.map( row => ({
			...row.data,
			id: row.key,
			hash: (opts.insecure === true ? row.data.hash : undefined)
		}) ).filter( row => opts.active == null || opts.active === row.active );

		return users;

	}
}

async function ip (opts = {}) {
	return await userOfType(IPUser, opts);
}

async function host (opts = {}) {
	return await userOfType(HostUser, opts);
}

async function named (opts = {}) {
	return await userOfType(NamedUser, opts);
}



module.exports = {
	ip,
	host,
	named,
}
