"use strict";

var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/asyncToGenerator"));
var _uuid = require("uuid");
var _testUtil = require("../../common/testUtil");
var _types = require("../../common/types");
var _Logger = _interopRequireDefault(require("../../Logger"));
var _request = require("./request");
var _mobiusSocket = require("../../mobius-socket");
var _Metrics = require("../../Metrics");
var _types2 = require("../../Metrics/types");
var _wsFeatureFlag = require("./wsFeatureFlag");
var _constants = require("./constants");
// Mock dependencies
jest.mock('../../mobius-socket', function () {
  return {
    getMobiusSocketInstance: jest.fn()
  };
});
jest.mock('../../Metrics', function () {
  return {
    getMetricManager: jest.fn()
  };
});
jest.mock('./wsFeatureFlag', function () {
  return {
    isMobiusWssEnabled: jest.fn()
  };
});
jest.mock('uuid', function () {
  return {
    v4: jest.fn()
  };
});
describe('APIRequest', function () {
  var webex;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  var mockMobiusSocket;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  var mockMetricManager;
  var infoSpy;
  var logSpy;
  var warnSpy;
  var errorSpy;
  beforeEach(function () {
    _request.APIRequest.resetInstance();
    webex = (0, _testUtil.getTestUtilsWebex)();
    jest.clearAllMocks();
    mockMobiusSocket = {
      connect: jest.fn().mockResolvedValue(undefined),
      disconnect: jest.fn().mockResolvedValue(undefined),
      sendWssRequest: jest.fn().mockResolvedValue({
        statusCode: 200,
        trackingId: 'test-tracking-id',
        data: {
          deviceId: 'test-device-id'
        }
      }),
      isConnected: jest.fn().mockReturnValue(false),
      getConnectedWebSocketUrl: jest.fn().mockReturnValue('wss://test.webex.com'),
      on: jest.fn(),
      off: jest.fn()
    };
    mockMetricManager = {
      submitMobiusSocketMetric: jest.fn()
    };
    _mobiusSocket.getMobiusSocketInstance.mockReturnValue(mockMobiusSocket);
    _Metrics.getMetricManager.mockReturnValue(mockMetricManager);
    _wsFeatureFlag.isMobiusWssEnabled.mockReturnValue(false);
    _uuid.v4.mockReturnValue('mock-uuid-12345');
    infoSpy = jest.spyOn(_Logger.default, 'info');
    logSpy = jest.spyOn(_Logger.default, 'log');
    warnSpy = jest.spyOn(_Logger.default, 'warn');
    errorSpy = jest.spyOn(_Logger.default, 'error');
  });
  afterEach(function () {
    jest.clearAllMocks();
  });
  describe('Constructor and singleton pattern', function () {
    it('should create instance with webex config and HTTP transport', function () {
      var apiRequest = _request.APIRequest.getInstance({
        webex: webex
      });
      expect(apiRequest).toBeDefined();
      expect(_mobiusSocket.getMobiusSocketInstance).toHaveBeenCalledWith(webex);
      expect(_Metrics.getMetricManager).toHaveBeenCalledWith(webex);
      expect(_wsFeatureFlag.isMobiusWssEnabled).toHaveBeenCalledWith(webex);
      expect(infoSpy).toHaveBeenCalledWith('APIRequest initialized with transport: HTTP', {
        file: 'REQUEST',
        method: 'constructor'
      });
    });
    it('should create instance with webex config and WSS transport when feature flag enabled', function () {
      _wsFeatureFlag.isMobiusWssEnabled.mockReturnValue(true);
      var apiRequest = _request.APIRequest.getInstance({
        webex: webex
      });
      expect(apiRequest).toBeDefined();
      expect(infoSpy).toHaveBeenCalledWith('APIRequest initialized with transport: WSS', {
        file: 'REQUEST',
        method: 'constructor'
      });
    });
    it('should throw error if webex is missing from config', function () {
      expect(function () {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        _request.APIRequest.getInstance({
          webex: undefined
        });
      }).toThrow('WebexSDK instance is required');
      expect(errorSpy).toHaveBeenCalledWith('APIRequest instantiation failed: WebexSDK instance is required', {
        file: 'REQUEST',
        method: 'constructor'
      });
    });
    it('should return same instance on subsequent getInstance() calls', function () {
      var instance1 = _request.APIRequest.getInstance({
        webex: webex
      });
      var instance2 = _request.APIRequest.getInstance({
        webex: webex
      });
      expect(instance1).toBe(instance2);
    });
    it('should clear singleton when resetInstance() is called', function () {
      var instance1 = _request.APIRequest.getInstance({
        webex: webex
      });
      _request.APIRequest.resetInstance();
      var instance2 = _request.APIRequest.getInstance({
        webex: webex
      });
      expect(instance1).not.toBe(instance2);
    });
  });
  describe('createAPIRequest factory', function () {
    it('should create APIRequest instance using factory function', function () {
      var apiRequest = (0, _request.createAPIRequest)({
        webex: webex
      });
      expect(apiRequest).toBeDefined();
      expect(apiRequest).toBeInstanceOf(_request.APIRequest);
    });
  });
  describe('isSocketEnabled', function () {
    it('should return false when WSS is disabled', function () {
      _wsFeatureFlag.isMobiusWssEnabled.mockReturnValue(false);
      var apiRequest = _request.APIRequest.getInstance({
        webex: webex
      });
      var result = apiRequest.isSocketEnabled();
      expect(result).toBe(false);
    });
    it('should return true when WSS is enabled', function () {
      _wsFeatureFlag.isMobiusWssEnabled.mockReturnValue(true);
      var apiRequest = _request.APIRequest.getInstance({
        webex: webex
      });
      var result = apiRequest.isSocketEnabled();
      expect(result).toBe(true);
    });
  });
  describe('connectToMobiusSocket', function () {
    it('should return immediately if socket is already connected', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
      var apiRequest, result;
      return _regenerator.default.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            mockMobiusSocket.isConnected.mockReturnValue(true);
            mockMobiusSocket.getConnectedWebSocketUrl.mockReturnValue('wss://existing.webex.com');
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            _context.next = 1;
            return apiRequest.connectToMobiusSocket('wss://test.webex.com');
          case 1:
            result = _context.sent;
            expect(result).toBe('wss://existing.webex.com');
            expect(mockMobiusSocket.connect).not.toHaveBeenCalled();
            expect(infoSpy).toHaveBeenCalledWith('Mobius WebSocket already connected', {
              file: 'REQUEST',
              method: 'connectToMobiusSocket'
            });
            expect(mockMetricManager.submitMobiusSocketMetric).not.toHaveBeenCalled();
          case 2:
          case "end":
            return _context.stop();
        }
      }, _callee);
    })));
    it('should initiate new connection if not connected', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2() {
      var apiRequest, wssUrl, result;
      return _regenerator.default.wrap(function (_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            mockMobiusSocket.isConnected.mockReturnValue(false);
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            wssUrl = 'wss://test.webex.com/api/v1';
            _context2.next = 1;
            return apiRequest.connectToMobiusSocket(wssUrl);
          case 1:
            result = _context2.sent;
            expect(mockMobiusSocket.connect).toHaveBeenCalledWith(wssUrl);
            expect(result).toBe(wssUrl);
            expect(infoSpy).toHaveBeenCalledWith('Mobius WebSocket not connected, initiating connection', {
              file: 'REQUEST',
              method: 'connectToMobiusSocket'
            });
          case 2:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    })));
    it('should submit success metric on successful connection', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee3() {
      var apiRequest, wssUrl;
      return _regenerator.default.wrap(function (_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            mockMobiusSocket.isConnected.mockReturnValue(false);
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            wssUrl = 'wss://mobius.webex.com/api/v1';
            _context3.next = 1;
            return apiRequest.connectToMobiusSocket(wssUrl);
          case 1:
            expect(logSpy).toHaveBeenCalledWith('Mobius WebSocket connected successfully', {
              file: 'REQUEST',
              method: 'connectToMobiusSocket'
            });
            expect(mockMetricManager.submitMobiusSocketMetric).toHaveBeenCalledWith(_types2.METRIC_EVENT.MOBIUS_SOCKET, _types2.MOBIUS_SOCKET_ACTION.CONNECT, _types2.METRIC_TYPE.BEHAVIORAL, wssUrl);
          case 2:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    })));
    it('should throw normalized error on connection failure', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee4() {
      var connectionError, apiRequest, wssUrl;
      return _regenerator.default.wrap(function (_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            connectionError = {
              statusCode: 503,
              statusMessage: 'Service Unavailable',
              trackingId: 'error-tracking-id',
              response: {
                statusCode: 503,
                trackingId: 'error-tracking-id',
                data: {
                  error: 'Connection failed'
                },
                metadata: {
                  'x-error': 'true'
                }
              }
            };
            mockMobiusSocket.isConnected.mockReturnValue(false);
            mockMobiusSocket.connect.mockRejectedValue(connectionError);
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            wssUrl = 'wss://mobius.webex.com/api/v1';
            _context4.next = 1;
            return expect(apiRequest.connectToMobiusSocket(wssUrl)).rejects.toEqual({
              statusCode: 503,
              body: {
                error: 'Connection failed'
              },
              headers: {
                trackingid: 'error-tracking-id',
                'x-error': 'true'
              }
            });
          case 1:
            expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Mobius WebSocket connection failed'), {
              file: 'REQUEST',
              method: 'connectToMobiusSocket'
            });
            expect(mockMetricManager.submitMobiusSocketMetric).toHaveBeenCalledWith(_types2.METRIC_EVENT.MOBIUS_SOCKET_ERROR, _types2.MOBIUS_SOCKET_ACTION.CONNECT, _types2.METRIC_TYPE.BEHAVIORAL, wssUrl, undefined, expect.any(String));
          case 2:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    })));
    it('should handle connection error with minimal error object', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee5() {
      var minimalError, apiRequest;
      return _regenerator.default.wrap(function (_context5) {
        while (1) switch (_context5.prev = _context5.next) {
          case 0:
            minimalError = {
              statusCode: 500
            };
            mockMobiusSocket.isConnected.mockReturnValue(false);
            mockMobiusSocket.connect.mockRejectedValue(minimalError);
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            _context5.next = 1;
            return expect(apiRequest.connectToMobiusSocket('wss://test.webex.com')).rejects.toEqual({
              statusCode: 500,
              body: undefined,
              headers: {
                trackingid: ''
              }
            });
          case 1:
          case "end":
            return _context5.stop();
        }
      }, _callee5);
    })));
  });
  describe('disconnectFromMobiusSocket', function () {
    it('should disconnect successfully', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee6() {
      var apiRequest;
      return _regenerator.default.wrap(function (_context6) {
        while (1) switch (_context6.prev = _context6.next) {
          case 0:
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            _context6.next = 1;
            return apiRequest.disconnectFromMobiusSocket();
          case 1:
            expect(mockMobiusSocket.disconnect).toHaveBeenCalledWith(undefined);
            expect(infoSpy).toHaveBeenCalledWith('Disconnecting from Mobius WebSocket', {
              file: 'REQUEST',
              method: 'disconnectFromMobiusSocket'
            });
            expect(logSpy).toHaveBeenCalledWith('Mobius WebSocket disconnected successfully', {
              file: 'REQUEST',
              method: 'disconnectFromMobiusSocket'
            });
          case 2:
          case "end":
            return _context6.stop();
        }
      }, _callee6);
    })));
    it('should submit success metric after disconnect', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee7() {
      var apiRequest;
      return _regenerator.default.wrap(function (_context7) {
        while (1) switch (_context7.prev = _context7.next) {
          case 0:
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            _context7.next = 1;
            return apiRequest.disconnectFromMobiusSocket();
          case 1:
            expect(mockMetricManager.submitMobiusSocketMetric).toHaveBeenCalledWith(_types2.METRIC_EVENT.MOBIUS_SOCKET, _types2.MOBIUS_SOCKET_ACTION.DISCONNECT, _types2.METRIC_TYPE.BEHAVIORAL, 'wss://test.webex.com');
          case 2:
          case "end":
            return _context7.stop();
        }
      }, _callee7);
    })));
    it('should disconnect with custom options', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee8() {
      var apiRequest, options;
      return _regenerator.default.wrap(function (_context8) {
        while (1) switch (_context8.prev = _context8.next) {
          case 0:
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            options = {
              code: 1000,
              reason: 'Normal closure'
            };
            _context8.next = 1;
            return apiRequest.disconnectFromMobiusSocket(options);
          case 1:
            expect(mockMobiusSocket.disconnect).toHaveBeenCalledWith(options);
          case 2:
          case "end":
            return _context8.stop();
        }
      }, _callee8);
    })));
    it('should handle disconnect error silently and log warning', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee9() {
      var apiRequest;
      return _regenerator.default.wrap(function (_context9) {
        while (1) switch (_context9.prev = _context9.next) {
          case 0:
            mockMobiusSocket.disconnect.mockRejectedValue(new Error('Disconnect failed'));
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            _context9.next = 1;
            return expect(apiRequest.disconnectFromMobiusSocket()).resolves.not.toThrow();
          case 1:
            expect(warnSpy).toHaveBeenCalledWith('Mobius WebSocket disconnection failed: Error: Disconnect failed', {
              file: 'REQUEST',
              method: 'disconnectFromMobiusSocket'
            });
          case 2:
          case "end":
            return _context9.stop();
        }
      }, _callee9);
    })));
    it('should submit error metric on disconnect failure', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee0() {
      var apiRequest;
      return _regenerator.default.wrap(function (_context0) {
        while (1) switch (_context0.prev = _context0.next) {
          case 0:
            mockMobiusSocket.disconnect.mockRejectedValue(new Error('Disconnect failed'));
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            _context0.next = 1;
            return apiRequest.disconnectFromMobiusSocket();
          case 1:
            expect(mockMetricManager.submitMobiusSocketMetric).toHaveBeenCalledWith(_types2.METRIC_EVENT.MOBIUS_SOCKET_ERROR, _types2.MOBIUS_SOCKET_ACTION.DISCONNECT, _types2.METRIC_TYPE.BEHAVIORAL, 'wss://test.webex.com', undefined, 'Error: Disconnect failed');
          case 2:
          case "end":
            return _context0.stop();
        }
      }, _callee0);
    })));
  });
  describe('makeRequest - HTTP transport', function () {
    it('should route through webex.request when WSS is disabled', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee1() {
      var apiRequest, requestOptions, expectedResponse, result;
      return _regenerator.default.wrap(function (_context1) {
        while (1) switch (_context1.prev = _context1.next) {
          case 0:
            _wsFeatureFlag.isMobiusWssEnabled.mockReturnValue(false);
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            requestOptions = {
              uri: '/api/v1/calling/web/device',
              method: _types.HTTP_METHODS.POST,
              body: {
                userId: 'user-123'
              }
            };
            expectedResponse = {
              statusCode: 200,
              body: {
                deviceId: 'device-456'
              }
            };
            webex.request.mockResolvedValue(expectedResponse);
            _context1.next = 1;
            return apiRequest.makeRequest(requestOptions);
          case 1:
            result = _context1.sent;
            expect(webex.request).toHaveBeenCalledWith(requestOptions);
            expect(result).toEqual(expectedResponse);
            expect(infoSpy).toHaveBeenCalledWith('Dispatching request via HTTP ', {
              file: 'REQUEST',
              method: 'makeRequest'
            });
          case 2:
          case "end":
            return _context1.stop();
        }
      }, _callee1);
    })));
    it('should pass request options unchanged to webex.request', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee10() {
      var apiRequest, requestOptions;
      return _regenerator.default.wrap(function (_context10) {
        while (1) switch (_context10.prev = _context10.next) {
          case 0:
            _wsFeatureFlag.isMobiusWssEnabled.mockReturnValue(false);
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            requestOptions = {
              uri: '/api/v1/calling/web/devices/device-123',
              method: _types.HTTP_METHODS.GET,
              headers: {
                'x-custom-header': 'value'
              }
            };
            webex.request.mockResolvedValue({
              statusCode: 200
            });
            _context10.next = 1;
            return apiRequest.makeRequest(requestOptions);
          case 1:
            expect(webex.request).toHaveBeenCalledWith(requestOptions);
          case 2:
          case "end":
            return _context10.stop();
        }
      }, _callee10);
    })));
    it('should return webex.request result directly', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee11() {
      var apiRequest, expectedResponse, result;
      return _regenerator.default.wrap(function (_context11) {
        while (1) switch (_context11.prev = _context11.next) {
          case 0:
            _wsFeatureFlag.isMobiusWssEnabled.mockReturnValue(false);
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            expectedResponse = {
              statusCode: 404,
              body: {
                error: 'Not found'
              },
              headers: {
                'x-tracking-id': 'track-123'
              }
            };
            webex.request.mockResolvedValue(expectedResponse);
            _context11.next = 1;
            return apiRequest.makeRequest({
              uri: '/api/v1/test',
              method: _types.HTTP_METHODS.GET
            });
          case 1:
            result = _context11.sent;
            expect(result).toEqual(expectedResponse);
          case 2:
          case "end":
            return _context11.stop();
        }
      }, _callee11);
    })));
  });
  describe('makeRequest - WebSocket transport', function () {
    beforeEach(function () {
      _wsFeatureFlag.isMobiusWssEnabled.mockReturnValue(true);
    });
    it('should derive socket message type from URI and method', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee12() {
      var apiRequest, requestOptions;
      return _regenerator.default.wrap(function (_context12) {
        while (1) switch (_context12.prev = _context12.next) {
          case 0:
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            requestOptions = {
              uri: '/api/v1/calling/web/device',
              method: _types.HTTP_METHODS.POST,
              body: {
                userId: 'user-123'
              }
            };
            _context12.next = 1;
            return apiRequest.makeRequest(requestOptions);
          case 1:
            expect(mockMobiusSocket.sendWssRequest).toHaveBeenCalledWith(expect.objectContaining({
              type: _constants.MOBIUS_SOCKET_MESSAGE_TYPE.REGISTER
            }));
            expect(infoSpy).toHaveBeenCalledWith('Dispatching request via WSS ', {
              file: 'REQUEST',
              method: 'makeRequest'
            });
          case 2:
          case "end":
            return _context12.stop();
        }
      }, _callee12);
    })));
    it('should throw error if message type is UNKNOWN', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee13() {
      var apiRequest, requestOptions;
      return _regenerator.default.wrap(function (_context13) {
        while (1) switch (_context13.prev = _context13.next) {
          case 0:
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            requestOptions = {
              uri: '/api/v1/unrecognized/path',
              method: _types.HTTP_METHODS.POST
            };
            _context13.next = 1;
            return expect(apiRequest.makeRequest(requestOptions)).rejects.toThrow('Unknown Mobius Socket message type: UNKNOWN');
          case 1:
            expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Unknown Mobius Socket message type'), {
              file: 'REQUEST',
              method: 'makeRequest'
            });
          case 2:
          case "end":
            return _context13.stop();
        }
      }, _callee13);
    })));
    it('should generate tracking ID with webex-js-sdk prefix', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee14() {
      var apiRequest, requestOptions;
      return _regenerator.default.wrap(function (_context14) {
        while (1) switch (_context14.prev = _context14.next) {
          case 0:
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            requestOptions = {
              uri: '/api/v1/calling/web/device',
              method: _types.HTTP_METHODS.POST
            };
            _context14.next = 1;
            return apiRequest.makeRequest(requestOptions);
          case 1:
            expect(_uuid.v4).toHaveBeenCalled();
            expect(mockMobiusSocket.sendWssRequest).toHaveBeenCalledWith(expect.objectContaining({
              trackingId: 'webex-js-sdk_mock-uuid-12345'
            }));
          case 2:
          case "end":
            return _context14.stop();
        }
      }, _callee14);
    })));
    it('should send WSS request with correct payload structure', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee15() {
      var apiRequest, requestOptions;
      return _regenerator.default.wrap(function (_context15) {
        while (1) switch (_context15.prev = _context15.next) {
          case 0:
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            requestOptions = {
              uri: '/api/v1/calling/web/device',
              method: _types.HTTP_METHODS.POST,
              body: {
                userId: 'user-123'
              },
              headers: {
                'x-custom': 'header-value'
              }
            };
            _context15.next = 1;
            return apiRequest.makeRequest(requestOptions);
          case 1:
            expect(mockMobiusSocket.sendWssRequest).toHaveBeenCalledWith({
              type: _constants.MOBIUS_SOCKET_MESSAGE_TYPE.REGISTER,
              trackingId: 'webex-js-sdk_mock-uuid-12345',
              metadata: {
                'x-custom': 'header-value',
                userAgent: 'webex-calling/beta',
                authorization: ''
              },
              data: {
                userId: 'user-123'
              }
            });
          case 2:
          case "end":
            return _context15.stop();
        }
      }, _callee15);
    })));
    it('should get user token for supplementary services (CALL_HOLD)', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee16() {
      var apiRequest, requestOptions;
      return _regenerator.default.wrap(function (_context16) {
        while (1) switch (_context16.prev = _context16.next) {
          case 0:
            webex.credentials.getUserToken.mockResolvedValue('Bearer token-abc-123');
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            requestOptions = {
              uri: '/api/v1/calling/web/devices/device-123/services/callhold/hold',
              method: _types.HTTP_METHODS.POST
            };
            _context16.next = 1;
            return apiRequest.makeRequest(requestOptions);
          case 1:
            expect(webex.credentials.getUserToken).toHaveBeenCalled();
            expect(mockMobiusSocket.sendWssRequest).toHaveBeenCalledWith(expect.objectContaining({
              type: _constants.MOBIUS_SOCKET_MESSAGE_TYPE.CALL_HOLD,
              metadata: expect.objectContaining({
                authorization: 'Bearer token-abc-123'
              })
            }));
          case 2:
          case "end":
            return _context16.stop();
        }
      }, _callee16);
    })));
    it('should not get user token for non-supplementary services', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee17() {
      var apiRequest, requestOptions;
      return _regenerator.default.wrap(function (_context17) {
        while (1) switch (_context17.prev = _context17.next) {
          case 0:
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            requestOptions = {
              uri: '/api/v1/calling/web/device',
              method: _types.HTTP_METHODS.POST
            };
            _context17.next = 1;
            return apiRequest.makeRequest(requestOptions);
          case 1:
            expect(webex.credentials.getUserToken).not.toHaveBeenCalled();
            expect(mockMobiusSocket.sendWssRequest).toHaveBeenCalledWith(expect.objectContaining({
              metadata: expect.objectContaining({
                authorization: ''
              })
            }));
          case 2:
          case "end":
            return _context17.stop();
        }
      }, _callee17);
    })));
    it('should normalize success response to WebexRequestPayload shape', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee18() {
      var wsResponse, apiRequest, result;
      return _regenerator.default.wrap(function (_context18) {
        while (1) switch (_context18.prev = _context18.next) {
          case 0:
            wsResponse = {
              type: 'register.response',
              statusCode: 201,
              statusMessage: 'Created',
              trackingId: 'track-123',
              data: {
                deviceId: 'device-456',
                correlationId: 'corr-789'
              },
              metadata: {
                'x-response-header': 'value'
              }
            };
            mockMobiusSocket.sendWssRequest.mockResolvedValue(wsResponse);
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            _context18.next = 1;
            return apiRequest.makeRequest({
              uri: '/api/v1/calling/web/device',
              method: _types.HTTP_METHODS.POST
            });
          case 1:
            result = _context18.sent;
            expect(result).toEqual({
              statusCode: 201,
              body: {
                deviceId: 'device-456',
                correlationId: 'corr-789'
              },
              headers: {
                trackingid: 'track-123',
                'x-response-header': 'value'
              }
            });
            expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('WSS request succeeded'), {
              file: 'REQUEST',
              method: 'makeRequest'
            });
          case 2:
          case "end":
            return _context18.stop();
        }
      }, _callee18);
    })));
    it('should normalize error to WebexRequestPayload shape', /*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee19() {
      var wsError, apiRequest;
      return _regenerator.default.wrap(function (_context19) {
        while (1) switch (_context19.prev = _context19.next) {
          case 0:
            wsError = {
              statusCode: 400,
              statusMessage: 'Bad Request',
              trackingId: 'error-track-456',
              response: {
                statusCode: 400,
                trackingId: 'error-track-456',
                data: {
                  error: 'Invalid request'
                },
                metadata: {
                  'x-error-code': 'ERR001'
                }
              }
            };
            mockMobiusSocket.sendWssRequest.mockRejectedValue(wsError);
            apiRequest = _request.APIRequest.getInstance({
              webex: webex
            });
            _context19.next = 1;
            return expect(apiRequest.makeRequest({
              uri: '/api/v1/calling/web/device',
              method: _types.HTTP_METHODS.POST
            })).rejects.toEqual({
              statusCode: 400,
              body: {
                error: 'Invalid request'
              },
              headers: {
                trackingid: 'error-track-456',
                'x-error-code': 'ERR001'
              }
            });
          case 1:
            expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('WSS request failed'), {
              file: 'REQUEST',
              method: 'makeRequest'
            });
          case 2:
          case "end":
            return _context19.stop();
        }
      }, _callee19);
    })));
  });
  describe('registerMobiusSocketListener', function () {
    it('should attach listener to event:async_event', function () {
      var apiRequest = _request.APIRequest.getInstance({
        webex: webex
      });
      var callback = jest.fn();
      apiRequest.registerMobiusSocketListener(callback);
      expect(mockMobiusSocket.on).toHaveBeenCalledWith('event:async_event', expect.any(Function));
      expect(infoSpy).toHaveBeenCalledWith('Attaching Mobius async event listener', {
        file: 'REQUEST',
        method: 'registerMobiusSocketListener'
      });
      expect(logSpy).toHaveBeenCalledWith('Mobius async event listener attached', {
        file: 'REQUEST',
        method: 'registerMobiusSocketListener'
      });
    });
    it('should invoke callback with event data when async event received', function () {
      var apiRequest = _request.APIRequest.getInstance({
        webex: webex
      });
      var callback = jest.fn();
      var mockEvent = {
        type: 'event:async_event',
        eventId: 'evt-123',
        trackingId: 'track-456',
        data: {
          eventType: 'registration.down'
        }
      };
      apiRequest.registerMobiusSocketListener(callback);
      var attachedCallback = mockMobiusSocket.on.mock.calls[0][1];
      attachedCallback(mockEvent);
      expect(callback).toHaveBeenCalledWith(mockEvent);
    });
    it('should submit LISTENER_REGISTERED metric', function () {
      var apiRequest = _request.APIRequest.getInstance({
        webex: webex
      });
      var callback = jest.fn();
      apiRequest.registerMobiusSocketListener(callback);
      expect(mockMetricManager.submitMobiusSocketMetric).toHaveBeenCalledWith(_types2.METRIC_EVENT.MOBIUS_SOCKET, _types2.MOBIUS_SOCKET_ACTION.LISTENER_REGISTERED, _types2.METRIC_TYPE.BEHAVIORAL);
    });
  });
  describe('unregisterMobiusSocketListener', function () {
    it('should detach listener from event:async_event', function () {
      var apiRequest = _request.APIRequest.getInstance({
        webex: webex
      });
      apiRequest.unregisterMobiusSocketListener();
      expect(mockMobiusSocket.off).toHaveBeenCalledWith('event:async_event');
      expect(infoSpy).toHaveBeenCalledWith('Detaching Mobius async event listener', {
        file: 'REQUEST',
        method: 'unregisterMobiusSocketListener'
      });
      expect(logSpy).toHaveBeenCalledWith('Mobius async event listener detached', {
        file: 'REQUEST',
        method: 'unregisterMobiusSocketListener'
      });
    });
    it('should submit LISTENER_UNREGISTERED metric', function () {
      var apiRequest = _request.APIRequest.getInstance({
        webex: webex
      });
      apiRequest.unregisterMobiusSocketListener();
      expect(mockMetricManager.submitMobiusSocketMetric).toHaveBeenCalledWith(_types2.METRIC_EVENT.MOBIUS_SOCKET, _types2.MOBIUS_SOCKET_ACTION.LISTENER_UNREGISTERED, _types2.METRIC_TYPE.BEHAVIORAL);
    });
  });
});
//# sourceMappingURL=request.test.js.map
