"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const query_1=require("@b/utils/query"),utils_1=require("../utils"),db_1=require("@b/db"),error_1=require("@b/utils/error"),utils_2=require("../utils");exports.metadata={summary:"Updates an existing role",operationId:"updateRole",tags:["Admin","CRM","Role"],logModule:"ADMIN_CRM",logTitle:"Update role",parameters:[{index:0,name:"id",in:"path",required:!0,description:"ID of the role to update",schema:{type:"string"}}],requestBody:{required:!0,description:"Updated data for the role",content:{"application/json":{schema:utils_1.roleUpdateSchema}}},responses:(0,query_1.updateRecordResponses)("Role"),requiresAuth:!0,permission:"edit.role"};exports.default=async e=>{const{body:s,params:r,user:o,ctx:t}=e,{id:i}=r,{name:a,permissions:d}=s;null==t||t.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||!l.role||"Super Admin"!==l.role.name)throw(0,error_1.createError)({statusCode:403,message:"Forbidden - Only Super Admins can update roles"});null==t||t.step("Fetching role");const n=await db_1.models.role.findByPk(i,{include:[{model:db_1.models.permission,as:"permissions"}]});if(!n)throw(0,error_1.createError)({statusCode:404,message:"Role not found"});null==t||t.step("Updating role details");a&&n.name!==a&&await n.update({name:a});if(d){null==t||t.step("Updating role permissions");const e=d.map(e=>Number(e));await n.setPermissions(e)}const u=await db_1.models.role.findByPk(i,{include:[{model:db_1.models.permission,as:"permissions"}]});null==t||t.step("Updating roles cache");await(0,utils_2.cacheRoles)();null==t||t.success();return{message:"Role updated successfully",role:u}};