const debug = require("debug");
const fetch = require("node-fetch");

const { version } = require("../../../package.json");

module.exports = async ({ account, adminkey, domain, generators, query }) => {
  const url = `https://${account}.${domain.replace(".io", ".net")}/${
    generators.endpoint
  }/__graphql`;

  debug("stepzen:dashboard")(`graphql url: ${url}`);
  debug("stepzen:dashboard")(`graphql query: ${query}`);

  const response = await fetch(url, {
    body: JSON.stringify({
      query,
    }),
    headers: {
      Authorization: `Apikey ${adminkey}`,
      "Content-Type": "application/json",
      "stepzen-cli-version": version,
      "user-agent": `stepzen-cli/${version}`,
    },
    method: "POST",
  });

  try {
    const result = await response.json();
    debug("stepzen:dashboard")(`graphql result: ${JSON.stringify(result, null, 2)}`);
    return result;
  } catch (error) {
    debug("stepzen:dashboard")(`graphql error: ${error.message}`);
    return [];
  }
};
