"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"),sequelize_1=require("sequelize"),error_1=require("@b/utils/error"),console_1=require("@b/utils/console");exports.metadata={summary:"Retrieves a specific support ticket by ID, including stats",operationId:"getSupportTicketById",tags:["Admin","CRM","Support Ticket"],parameters:[{index:0,name:"id",in:"path",required:!0,description:"ID of the support ticket to retrieve",schema:{type:"string"}}],responses:{200:{description:"Support ticket details, with user and agent stats",content:{"application/json":{schema:{type:"object",properties:{...utils_1.supportTicketSchema,userStats:{type:"object",properties:{totalTickets:{type:"number"},resolvedTickets:{type:"number"}}},agentStats:{type:"object",properties:{avgRating:{type:"number",nullable:!0},resolved:{type:"number"}},nullable:!0}}}}}},401:query_1.unauthorizedResponse,404:(0,query_1.notFoundMetadataResponse)("Support ticket not found"),500:query_1.serverErrorResponse},requiresAuth:!0,permission:"view.support.ticket",logModule:"ADMIN_CRM",logTitle:"Get Support Ticket",demoMask:["user.email","agent.email"]};exports.default=async e=>{var t;const{params:r,ctx:s}=e;try{if(!(null==r?void 0:r.id)||"string"!=typeof r.id)throw(0,error_1.createError)({statusCode:400,message:"Invalid ticket ID format"});if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r.id))throw(0,error_1.createError)({statusCode:400,message:"Invalid ticket ID format"});null==s||s.step("Fetching support ticket");let e,a;try{e=await db_1.models.supportTicket.findOne({where:{id:r.id},include:[{model:db_1.models.user,as:"agent",attributes:["id","avatar","firstName","lastName","lastLogin"]},{model:db_1.models.user,as:"user",attributes:["id","firstName","lastName","email","avatar"]}]})}catch(e){console_1.logger.error("TICKET",`Database error fetching ticket ${r.id}`,e);throw(0,error_1.createError)({statusCode:500,message:"Database connection error"})}if(!e)throw(0,error_1.createError)({statusCode:404,message:"Support ticket not found"});try{a=e.get({plain:!0})}catch(e){console_1.logger.error("TICKET","Error extracting ticket data",e);throw(0,error_1.createError)({statusCode:500,message:"Failed to process ticket data"})}if("string"==typeof a.messages)try{const e=JSON.parse(a.messages);a.messages=Array.isArray(e)?e:[]}catch(e){console_1.logger.error("TICKET",`Failed to parse messages JSON for ticket ${a.id}`,e);console_1.logger.debug("TICKET",`Problematic messages value: ${a.messages}`);a.messages=[]}if("string"==typeof a.tags)try{const e=JSON.parse(a.tags);a.tags=Array.isArray(e)?e:[]}catch(e){console_1.logger.error("TICKET",`Failed to parse tags JSON for ticket ${a.id}`,e);console_1.logger.debug("TICKET",`Problematic tags value: ${a.tags}`);a.tags=[]}a.messages=a.messages||[];a.tags=a.tags||[];const o=a.userId;let i={totalTickets:0,resolvedTickets:0};if(o)try{const[e,t]=await Promise.all([db_1.models.supportTicket.count({where:{userId:o}}),db_1.models.supportTicket.count({where:{userId:o,status:"CLOSED"}})]);i={totalTickets:e,resolvedTickets:t}}catch(e){console_1.logger.error("TICKET","Error fetching user stats",e);i={totalTickets:0,resolvedTickets:0}}let l=null;const c=a.agentId;if(c)try{const[e,r]=await Promise.all([db_1.models.supportTicket.count({where:{agentId:c,status:"CLOSED"}}),db_1.models.supportTicket.findAll({where:{agentId:c,satisfaction:{[sequelize_1.Op.not]:null}},attributes:[[(0,sequelize_1.fn)("AVG",(0,sequelize_1.col)("satisfaction")),"avgRating"]],raw:!0})]);l={resolved:e,avgRating:(null===(t=r[0])||void 0===t?void 0:t.avgRating)?parseFloat(r[0].avgRating):null}}catch(e){console_1.logger.error("TICKET","Error fetching agent stats",e);l={avgRating:null,resolved:0}}null==s||s.success("Support ticket retrieved successfully");return{...a,userStats:i,agentStats:l}}catch(e){console_1.logger.error("TICKET","Error fetching support ticket",e);if(e.statusCode)throw e;throw(0,error_1.createError)({statusCode:500,message:"Internal server error"})}};