"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get deleteRoleById () {
        return deleteRoleById;
    },
    get getDeletableRoleOrThrow () {
        return getDeletableRoleOrThrow;
    }
});
const _expressasynchandler = /*#__PURE__*/ _interop_require_default(require("express-async-handler"));
const _errors = require("@tamanu/errors");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
let InvalidRoleDeletionError = class InvalidRoleDeletionError extends _errors.DatabaseConstraintError {
    constructor(/** @type {string} */ roleId, /** @type {number} */ assignedUserCount){
        const isSingular = assignedUserCount === 1;
        const unit = isSingular ? 'user' : 'users';
        super(`Cannot delete role with ID ‘${roleId}’. ${assignedUserCount}\u{00A0}${unit} assigned to it.`);
        this.withExtraData({
            assignedUserCount
        });
    }
};
const getDeletableRoleOrThrow = async (models, roleId)=>{
    if (!models.Role.sequelize?.isInsideTransaction?.()) {
        throw new Error('DEV ERROR: getDeletableRoleOrThrow must be run in a transaction');
    }
    const role = await models.Role.findByPk(roleId);
    if (!role) throw new _errors.NotFoundError(`No role found with ID ‘${roleId}’`);
    const assignedUserCount = await models.User.count({
        where: {
            role: role.id
        }
    });
    if (assignedUserCount > 0) throw new InvalidRoleDeletionError(roleId, assignedUserCount);
    return role;
};
const deleteRoleById = (0, _expressasynchandler.default)(async (req, res)=>{
    req.checkPermission('delete', 'Role');
    const { store: { models, sequelize }, params: { id } } = req;
    await sequelize.transaction(async ()=>{
        const role = await getDeletableRoleOrThrow(models, id);
        await role.destroy();
    });
    res.status(204).send();
});

//# sourceMappingURL=roles.delete.js.map