"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:"Reply to a support ticket",description:"Reply to a support ticket identified by its UUID.",operationId:"replyTicket",tags:["Support"],requiresAuth:!0,logModule:"USER",logTitle:"Reply to 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")};exports.default=async e=>{const{params:t,user:s,body:r,ctx:a}=e,{id:i}=t;if(!(null==s?void 0:s.id)){null==a||a.fail("User not authenticated");throw(0,error_1.createError)(401,"Unauthorized")}null==a||a.step("Finding support 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:["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("Ticket is closed");throw(0,error_1.createError)(403,"Cannot reply to a closed ticket")}null==a||a.step("Validating message");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")}if("client"!==n&&"agent"!==n){null==a||a.fail("Invalid message type");throw(0,error_1.createError)(400,"Invalid message type")}if(d!==s.id){null==a||a.fail("Unauthorized to send message");throw(0,error_1.createError)(403,"You are not authorized to send this message")}let c=!1;if("agent"===n&&!o.agentId){o.agentId=s.id;const e=await db_1.models.user.findByPk(s.id);o.agentName=e&&(e.firstName||e.lastName)?[e.firstName,e.lastName].filter(Boolean).join(" "):(null==e?void 0:e.email)||"";c=!0}let m=[];if(o.messages)if(Array.isArray(o.messages))m=[...o.messages];else if("string"==typeof o.messages)try{const e=JSON.parse(o.messages);m=Array.isArray(e)?e:[]}catch(e){console_1.logger.error("SUPPORT","Failed to parse messages JSON",e);m=[]}const g={type:n,time:l,userId:d,text:u,...p?{attachment:p}:{}};m.push(g);if("agent"===n&&!o.responseTime&&c){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 with new message");await o.update({messages:m,status:"client"===n?"REPLIED":"OPEN",...c&&{agentId:o.agentId,agentName:o.agentName},...o.responseTime&&{responseTime:o.responseTime}});null==a||a.step("Broadcasting reply via WebSocket");Websocket_1.messageBroker.broadcastToSubscribedClients("/api/user/support/ticket",{id:i},{method:"reply",data:{message:{type:n,time:l,userId:d,text:u,attachment:p},status:o.status,updatedAt:new Date}});null==a||a.success("Reply sent successfully");return{message:"Reply sent",data:o.get({plain:!0})}};