import { GetMessagesRequest, GetMessagesResponse, GetTicketsRequest, GetTicketsResponse, SendTicketMessageRequest, } from "@root/model/ticket"; import { authStore } from "@root/stores/auth"; import ReconnectingEventSource from "reconnecting-eventsource"; const supportApiUrl = "https://admin.pena.digital/heruvym"; const makeRequest = authStore.getState().makeRequest; export function subscribeToAllTickets({ onMessage, onError, accessToken, }: { accessToken: string; onMessage: (e: MessageEvent) => void; onError: (e: Event) => void; }) { const url = `${supportApiUrl}/subscribe?Authorization=${accessToken}`; const eventSource = createEventSource(onMessage, onError, url); return () => { eventSource.close(); }; } export function subscribeToTicketMessages({ onMessage, onError, accessToken, ticketId, }: { accessToken: string; ticketId: string; onMessage: (e: MessageEvent) => void; onError: (e: Event) => void; }) { const url = `${supportApiUrl}/ticket?ticket=${ticketId}&Authorization=${accessToken}`; const eventSource = createEventSource(onMessage, onError, url); return () => { eventSource.close(); }; } export async function getTickets({ body, signal, }: { body: GetTicketsRequest; signal: AbortSignal; }): Promise { return makeRequest({ url: `${supportApiUrl}/getTickets`, method: "POST", useToken: true, body, signal, }); } export async function getTicketMessages({ body, signal, }: { body: GetMessagesRequest; signal: AbortSignal; }): Promise { return makeRequest({ url: `${supportApiUrl}/getMessages`, method: "POST", useToken: true, body, signal, }).then((response) => { const result = (response as any).data as GetMessagesResponse; return result; }); } export async function sendTicketMessage({ body }: { body: SendTicketMessageRequest; }) { return makeRequest({ url: `${supportApiUrl}/send`, method: "POST", useToken: true, body, }); } function createEventSource(onMessage: (e: MessageEvent) => void, onError: (e: Event) => void, url: string) { const eventSource = new ReconnectingEventSource(url); eventSource.addEventListener("open", () => console.log(`EventSource connected with ${url}`)); eventSource.addEventListener("close", () => console.log(`EventSource closed with ${url}`)); eventSource.addEventListener("message", onMessage); eventSource.addEventListener("error", onError); return eventSource; }