// Copyright (c) 2020,2021, StepZen, Inc.

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

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

const proxy = async (req, res) => {
  const { account, adminkey, domain, workspace } = req;

  const url = `https://${account}.${domain.replace(".io", ".net")}/${
    workspace.endpoint
  }/__graphql`;

  debug("stepzen:proxy")(url);

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

  res.json(json);
};

module.exports = proxy;
