"use strict";

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

var _graphqlTag = _interopRequireDefault(require("graphql-tag"));

var _api = _interopRequireDefault(require("../api"));

var _tracker = require("../tracker");

var exit = _interopRequireWildcard(require("../cli/exit"));

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * 
 * @format
 */

/**
 * External dependencies
 */

/**
 * Internal dependencies
 */
async function isMultiSiteInSiteMeta(appId, envId) {
  var _res, _res$data, _res$data$app;

  const track = _tracker.trackEventWithEnv.bind(null, appId, envId);

  const api = await (0, _api.default)();
  let res;

  try {
    res = await api.query({
      query: (0, _graphqlTag.default)`query AppMultiSiteCheck( $appId: Int, $envId: Int) {
				app(id: $appId) {
					id
					name
					repo
					environments(id: $envId) {
						id
						appId
						name
						type
						isMultisite
						isSubdirectoryMultisite
					}
				}
			}`,
      variables: {
        appId,
        envId
      }
    });
  } catch (GraphQlError) {
    await track('import_sql_command_error', {
      error_type: 'GraphQL-MultiSite-Check-failed',
      gql_err: GraphQlError
    });
    exit.withError(`StartImport call failed: ${GraphQlError}`);
  }

  if (Array.isArray((_res = res) === null || _res === void 0 ? void 0 : (_res$data = _res.data) === null || _res$data === void 0 ? void 0 : (_res$data$app = _res$data.app) === null || _res$data$app === void 0 ? void 0 : _res$data$app.environments)) {
    const environments = res.data.app.environments;

    if (!environments.length) {
      return false;
    } // we asked for one result with one appId and one envId, so...


    const thisEnv = environments[0];

    if (thisEnv.isMultiSite || thisEnv.isSubdirectoryMultisite) {
      return true;
    }
  }

  return false;
}