"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.handleMockApi = handleMockApi;
exports.mockApiHandler = mockApiHandler;

var _fs = require("fs");

var _httpProxyMiddleware = require("http-proxy-middleware");

var _constants = require("../constants");

var _logger = require("../../logger");

function mockApiHandler(app, options) {
  const {
    enable,
    separateSeverPort,
    mockEntryFile,
    mockPrefix
  } = options.mockServer;

  if (!enable) {
    return;
  }

  if (separateSeverPort) {
    app.use(mockPrefix, (0, _httpProxyMiddleware.createProxyMiddleware)({
      // eslint-disable-next-line no-useless-concat
      target: 'ht' + `tp://localhost:${separateSeverPort}`,
      changeOrigin: true
    }));
    (0, _logger.messageLogger)(`Please make sure you run mock Server separately in specified port (${separateSeverPort})`);
    (0, _logger.messageLogger)(`If not running already you can run "cbt mock:server --mock_port=${separateSeverPort}"`);
  } else {
    // eslint-disable-next-line no-use-before-define
    handleMockApi(mockEntryFile, app);
  }
}

function handleMockApi(mockEntryFile, app) {
  const entryFilePath = (0, _constants.joinWithAppPath)(mockEntryFile); // eslint-disable-next-line no-use-before-define

  const mockFunc = safeRequire(entryFilePath);
  console.log(mockFunc);
  mockFunc?.mockApi?.(app);
} // function handleMockApi(params) {
// }


function safeRequire(entryFilePath) {
  if (!(0, _fs.existsSync)(entryFilePath)) {
    return null;
  } // eslint-disable-next-line import/no-dynamic-require, global-require


  return require(entryFilePath);
}