"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const db_1=require("@b/db"),utils_1=require("../utils"),query_1=require("@b/utils/query"),error_1=require("@b/utils/error"),console_1=require("@b/utils/console");exports.metadata={summary:"Deletes a role",operationId:"deleteRole",tags:["Admin","CRM","Role"],logModule:"ADMIN_CRM",logTitle:"Delete role",parameters:[{index:0,name:"id",in:"path",description:"ID of the role to delete",required:!0,schema:{type:"number"}}],permission:"delete.role",responses:(0,query_1.deleteRecordResponses)("Role"),requiresAuth:!0};exports.default=async e=>{const{params:r,user:o,ctx:s}=e,{id:t}=r;null==s||s.step("Validating user authorization");if(!(null==o?void 0:o.id))throw(0,error_1.createError)({statusCode:401,message:"Unauthorized"});const l=await db_1.models.user.findByPk(o.id,{include:[{model:db_1.models.role,as:"role"}]});if(!l||"Super Admin"!==l.role.name)throw(0,error_1.createError)({statusCode:403,message:"Forbidden - Only Super Admins can delete roles"});null==s||s.step("Validating role");const a=await db_1.models.role.findByPk(t);if(!a)throw(0,error_1.createError)({statusCode:404,message:"Role not found"});if("Super Admin"===a.name)throw(0,error_1.createError)({statusCode:403,message:"Forbidden - Cannot delete the Super Admin role"});try{null==s||s.step("Deleting role and permissions");await db_1.sequelize.transaction(async e=>{await db_1.models.rolePermission.destroy({where:{roleId:t},transaction:e});await db_1.models.role.destroy({where:{id:t},transaction:e})});null==s||s.step("Rebuilding roles cache");await(0,utils_1.cacheRoles)();null==s||s.success();return{message:"Role removed successfully"}}catch(e){console_1.logger.error("ROLE","Transaction failed",e);throw(0,error_1.createError)({statusCode:500,message:"Failed to remove the role"})}};