"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.metadata=void 0;const console_1=require("@b/utils/console"),db_1=require("@b/db");exports.metadata={requiresAuth:!0,summary:"WebSocket endpoint for support ticket real-time updates",description:"Allows users and admins to subscribe to ticket updates and receive real-time messages"};exports.default=async(e,s)=>{try{let r;if("string"==typeof s)try{r=JSON.parse(s)}catch(e){console_1.logger.error("TICKET_WS","Invalid JSON message",e);return}else r=s;if(!r||!r.payload){console_1.logger.error("TICKET_WS","Invalid message structure: payload is missing",new Error("Missing payload"));return}const{action:t,payload:o}=r;if(!t){console_1.logger.error("TICKET_WS","Invalid message structure: action is missing",new Error("Missing action field"));return}const i=e.user,n=null==i?void 0:i.id;console_1.logger.debug("TICKET_WS",`Received action: ${t} from user: ${n}`);switch(t){case"SUBSCRIBE":if(o.id){console_1.logger.debug("TICKET_WS",`User ${n} subscribing to ticket: ${o.id}`);if(!n){console_1.logger.warn("TICKET_WS","No user ID provided for ticket subscription");return{type:"subscription",status:"error",message:"Authentication required"}}const e=await db_1.models.supportTicket.findOne({where:{id:o.id}});if(!e){console_1.logger.error("TICKET_WS",`Ticket ${o.id} not found in database`);return{type:"subscription",status:"error",message:"Ticket not found"}}console_1.logger.debug("TICKET_WS",`Found ticket: ${e.id}, userId: ${e.userId}, type: ${e.type}`);let s=!1;try{if(e.userId===n){s=!0;console_1.logger.debug("TICKET_WS",`User ${n} is the ticket owner`)}else{const e=await db_1.models.user.findByPk(n);if(e&&(0===e.roleId||1===e.roleId||2===e.roleId)){s=!0;console_1.logger.debug("TICKET_WS",`User ${n} is admin (roleId: ${e.roleId})`)}else console_1.logger.debug("TICKET_WS",`User ${n} is not admin and not ticket owner`)}}catch(r){console_1.logger.error("TICKET_WS",`Error checking user access: ${r.message}`);s=e.userId===n}if(s){const s=`ticket-${o.id}`;console_1.logger.debug("TICKET_WS",`Successfully granting access for ${n} to ${s}`);return{type:"subscription",status:"success",message:`Subscribed to ticket ${o.id}`,data:{ticketId:e.id,type:e.type,status:e.status}}}console_1.logger.warn("TICKET_WS",`User ${n} denied access to ticket ${o.id} (owner: ${e.userId})`);return{type:"subscription",status:"error",message:"Unauthorized access to ticket"}}break;case"UNSUBSCRIBE":if(o.id){console_1.logger.debug("TICKET_WS",`User ${n} unsubscribing from ticket: ${o.id}`);o.id;return{type:"subscription",status:"success",message:`Unsubscribed from ticket ${o.id}`}}break;default:console_1.logger.warn("TICKET_WS",`Unknown action: ${t}`)}}catch(e){console_1.logger.error("TICKET_WS","Error handling support ticket websocket message",e)}};