import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { useCallback, useMemo } from 'react';
import { request } from '@atlaskit/linking-common';
import { fg } from '@atlaskit/platform-feature-flags';
import { getCurrentSiteCloudId } from '../../services/current-site-cloud-id';
import { queryIncomingOutgoingLinks as queryIncomingOutgoingAris } from './query';
/**
 * @param baseUriWithNoTrailingSlash base url which will then be appended with /gateway/api/graphql to make requests to AGG
 */
var useIncomingOutgoingAri = function useIncomingOutgoingAri() {
  var baseUriWithNoTrailingSlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var aggRequestCall = useCallback( /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(body, headers) {
      return _regeneratorRuntime.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            return _context.abrupt("return", request('post', baseUriWithNoTrailingSlash + '/gateway/api/graphql', body, headers, [200]));
          case 1:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x, _x2) {
      return _ref.apply(this, arguments);
    };
  }(), [baseUriWithNoTrailingSlash]);
  var getCurrentSiteId = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var response, _t;
    return _regeneratorRuntime.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.prev = 0;
          _context2.next = 1;
          return request('get', baseUriWithNoTrailingSlash + '/_edge/tenant_info');
        case 1:
          response = _context2.sent;
          return _context2.abrupt("return", response === null || response === void 0 ? void 0 : response.cloudId);
        case 2:
          _context2.prev = 2;
          _t = _context2["catch"](0);
          return _context2.abrupt("return", undefined);
        case 3:
        case "end":
          return _context2.stop();
      }
    }, _callee2, null, [[0, 2]]);
  })), [baseUriWithNoTrailingSlash]);
  var getSiteId = useCallback( /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(resourceAri) {
      var ariPattern, match, _t2;
      return _regeneratorRuntime.wrap(function (_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            // ARI pattern that matches both formats:
            // - New format: ari:cloud:<resource_owner>::<resource_type>/<resource_id>
            // - Legacy format: ari:cloud:<resource_owner>:<cloud_id>:<resource_type>/<resource_id>
            //
            // Capture groups:
            // 1: resource_owner - [a-z][a-z.-]+
            // 2: cloud_id (siteId) - [a-zA-Z0-9_.-]+ (empty for new format, but since we need to return the siteId, we only use legacy one)
            // 3: resource_type - [a-z][a-zA-Z.-]
            // 4: resource_id
            //
            // See https://developer.atlassian.com/platform/atlassian-resource-identifier/spec/ari-latest/#syntax for more details
            ariPattern = /^ari:cloud:([a-z][a-z.-]+):([a-zA-Z0-9_.-]+):([a-z][a-zA-Z.-]+)\/(.+)$/;
            match = resourceAri.match(ariPattern);
            if (!(match && match[2])) {
              _context3.next = 1;
              break;
            }
            return _context3.abrupt("return", match[2]);
          case 1:
            if (!fg('platform_sl_incoming_outgoing_tenant_info_killswitch')) {
              _context3.next = 3;
              break;
            }
            _context3.next = 2;
            return getCurrentSiteCloudId(baseUriWithNoTrailingSlash);
          case 2:
            _t2 = _context3.sent;
            _context3.next = 5;
            break;
          case 3:
            _context3.next = 4;
            return getCurrentSiteId();
          case 4:
            _t2 = _context3.sent;
          case 5:
            return _context3.abrupt("return", _t2);
          case 6:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    return function (_x3) {
      return _ref3.apply(this, arguments);
    };
  }(), [getCurrentSiteId, baseUriWithNoTrailingSlash]);
  var getIncomingOutgoingAris = useCallback(
  /*#__PURE__*/
  /**
   * Returning aris linking to (outgoing) and from (incoming) a given ari from AGS using
   * https://developer.atlassian.com/cloud/ari-graph-store/relationships/content-referenced-entity/#query
   * @param ari the ari for which the incoming outgoing aris are to be retrieved
   * @param firstIncoming The maximum count of incoming relationships to fetch. Must not exceed 1000. This max limit is handled by AGG itself. Default is 50 (ORS batch max limit)
   * @param firstOutgoing The maximum count of outgoing relationships to fetch. Must not exceed 1000. This max limit is handled by AGG itself. Default is 50 (ORS batch max limit)
   *
   */
  function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(ari) {
      var _response$data$graphS, _response$data, _response$data$graphS2, _response$data2;
      var firstIncoming,
        firstOutgoing,
        siteId,
        headers,
        response,
        incomingAris,
        outgoingAris,
        _args4 = arguments;
      return _regeneratorRuntime.wrap(function (_context4) {
        while (1) switch (_context4.prev = _context4.next) {
          case 0:
            firstIncoming = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : 50;
            firstOutgoing = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : 50;
            _context4.next = 1;
            return getSiteId(ari);
          case 1:
            siteId = _context4.sent;
            if (siteId) {
              _context4.next = 2;
              break;
            }
            return _context4.abrupt("return", {
              incomingAris: [],
              outgoingAris: []
            });
          case 2:
            headers = {
              'X-Query-Context': "ari:cloud:platform::site/".concat(siteId)
            };
            _context4.next = 3;
            return aggRequestCall({
              variables: {
                id: ari,
                firstIncoming: firstIncoming,
                firstOutgoing: firstOutgoing
              },
              query: queryIncomingOutgoingAris
            }, headers);
          case 3:
            response = _context4.sent;
            incomingAris = (_response$data$graphS = response === null || response === void 0 || (_response$data = response.data) === null || _response$data === void 0 || (_response$data = _response$data.graphStore) === null || _response$data === void 0 || (_response$data = _response$data.incoming) === null || _response$data === void 0 || (_response$data = _response$data.aris) === null || _response$data === void 0 || (_response$data = _response$data.map(function (node) {
              return node === null || node === void 0 ? void 0 : node.id;
            })) === null || _response$data === void 0 ? void 0 : _response$data.filter(function (id) {
              return !!id;
            })) !== null && _response$data$graphS !== void 0 ? _response$data$graphS : [];
            outgoingAris = (_response$data$graphS2 = response === null || response === void 0 || (_response$data2 = response.data) === null || _response$data2 === void 0 || (_response$data2 = _response$data2.graphStore) === null || _response$data2 === void 0 || (_response$data2 = _response$data2.outgoing) === null || _response$data2 === void 0 || (_response$data2 = _response$data2.aris) === null || _response$data2 === void 0 || (_response$data2 = _response$data2.map(function (node) {
              return node === null || node === void 0 ? void 0 : node.id;
            })) === null || _response$data2 === void 0 ? void 0 : _response$data2.filter(function (id) {
              return !!id;
            })) !== null && _response$data$graphS2 !== void 0 ? _response$data$graphS2 : [];
            return _context4.abrupt("return", {
              incomingAris: incomingAris,
              outgoingAris: outgoingAris
            });
          case 4:
          case "end":
            return _context4.stop();
        }
      }, _callee4);
    }));
    return function (_x4) {
      return _ref4.apply(this, arguments);
    };
  }(), [aggRequestCall, getSiteId]);
  return useMemo(function () {
    return {
      getIncomingOutgoingAris: getIncomingOutgoingAris
    };
  }, [getIncomingOutgoingAris]);
};
export default useIncomingOutgoingAri;