/**
 * Create socket connection
 */
import io from "socket.io-client"
import { getUserToken } from "./sessionHandler"
import log from "@racletteCore/lib/logger"

/**
 * createSocket returns an instance of a custom SocketClient
 * @param {string} host - our socket endpoint
 * @param {string} appSessionId - The id for the current application - server session
 * @param {object} opts - socket.io options (can include sessionId for work sessions)
 */

const createSocket = (host, appSessionId, opts: { sessionId?: string } = {}) => {
  log.socket("createSocket", { host, appSessionId, opts })
  const token = getUserToken()
  const defaults = {
    cors: {
      origin: /localhost/,
    },
    transports: ["polling", "websocket"],
    withCredentials: true,
    auth: {
      ...(token ? { token } : {}),
      ...(opts.sessionId ? { sessionId: opts.sessionId } : {}),
    },
    extraHeaders: {
      "app-session-id": appSessionId,
    },
  }
  const socket = io(host, { ...defaults, ...opts })

  return socket
}

export default createSocket
export { createSocket }
