"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const db_1=require("@b/db"),Websocket_1=require("@b/handler/Websocket"),error_1=require("@b/utils/error"),query_1=require("@b/utils/query"),console_1=require("@b/utils/console");exports.metadata={summary:"Admin reply to a support ticket",description:"Admin reply to a support ticket identified by its UUID.",operationId:"adminReplyTicket",tags:["Admin","CRM","Support Ticket"],requiresAuth:!0,permission:"edit.support.ticket",parameters:[{index:0,name:"id",in:"path",required:!0,description:"The UUID of the ticket to reply to",schema:{type:"string"}}],requestBody:{description:"The message to send",required:!0,content:{"application/json":{schema:{type:"object",properties:{type:{type:"string",enum:["client","agent"]},time:{type:"string",format:"date-time"},userId:{type:"string"},text:{type:"string"},attachment:{type:"string"}},required:["type","time","userId","text"]}}}},responses:(0,query_1.updateRecordResponses)("Support Ticket"),logModule:"ADMIN_SUP",logTitle:"Reply to ticket"};exports.default=async e=>{const{params:t,user:s,body:r,ctx:a}=e,{id:i}=t;if(!(null==s?void 0:s.id))throw(0,error_1.createError)(401,"Unauthorized");null==a||a.step("Fetching ticket");const o=await db_1.models.supportTicket.findByPk(i,{include:[{model:db_1.models.user,as:"agent",attributes:["avatar","firstName","lastName","lastLogin"]},{model:db_1.models.user,as:"user",attributes:["id","firstName","lastName","email"]}]});if(!o){null==a||a.fail("Ticket not found");throw(0,error_1.createError)(404,"Ticket not found")}if("CLOSED"===o.status){null==a||a.fail("Cannot reply to closed ticket");throw(0,error_1.createError)(403,"Cannot reply to a closed ticket")}const{type:n,time:l,userId:d,text:u,attachment:p}=r;if(!(n&&l&&d&&u)){null==a||a.fail("Invalid message structure");throw(0,error_1.createError)(400,"Invalid message structure")}null==a||a.step("Fetching admin user info");const c=await db_1.models.user.findByPk(s.id),m=c&&(c.firstName||c.lastName)?[c.firstName,c.lastName].filter(Boolean).join(" "):(null==c?void 0:c.email)||"Support Agent";let g=!1;if(!o.agentId){null==a||a.step("Auto-assigning agent");o.agentId=s.id;o.agentName=m;g=!0}null==a||a.step("Preparing reply message");let y=[];if(o.messages)if(Array.isArray(o.messages))y=[...o.messages];else if("string"==typeof o.messages)try{const e=JSON.parse(o.messages);y=Array.isArray(e)?e:[]}catch(e){console_1.logger.error("SUPPORT","Failed to parse messages JSON",e);y=[]}const f={id:s.id,firstName:s.firstName,lastName:s.lastName,avatar:s.avatar},b={type:"agent",time:l,userId:s.id,text:u,senderName:m,agentProfile:f,...p?{attachment:p}:{}};y.push(b);if(!o.responseTime&&g){const e=new Date(o.createdAt),t=new Date(l);o.responseTime=Math.round((t.getTime()-e.getTime())/6e4)}null==a||a.step("Updating ticket");await o.update({messages:y,status:"REPLIED",...g&&{agentId:o.agentId,agentName:o.agentName},...o.responseTime&&{responseTime:o.responseTime}});null==a||a.step("Broadcasting to clients");o.userId;Websocket_1.messageBroker.broadcastToSubscribedClients("/api/user/support/ticket",{id:i},{method:"reply",payload:{id:i,message:b,status:o.status,updatedAt:new Date}});null==a||a.success("Reply sent successfully");return{message:"Reply sent successfully",data:o.get({plain:!0})}};