import { HttpError } from '../src/errors.js';

function checkAbility(user, subject, action) {
	if (!user?.abilities) {
		return null;
	}

	if (subject && action) {
		return user.abilities.some((ability) => ability.subject === subject && ability.action === action);
	}

	if (subject) {
		return user.abilities.some((ability) => ability[subject] === true || (ability.subject === subject && !ability.action));
	}

	return false;
}

export default function verifyAbility(user, subject, action, options = {}) {
	const isAble = checkAbility(user, subject, action);

	if (!isAble && options.throwError) {
		throw new HttpError(`Insufficient privileges for ${[subject, action].filter(Boolean).join()}`, 403);
	}

	return isAble;
}
