// 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, domain, predicates, workspace } = req;

  let endpoint = workspace.endpoint;

  let headers = {};

  if (predicates.available && predicates.enabled) {
    try {
      const others = JSON.parse(JSON.stringify(predicates.headers));
      headers = {
        ...others,
      };
    } catch {}
  } else {
    headers = {
      Authorization: `Apikey ${adminkey}`,
    };
  }

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

  debug("stepzen:dashboard")(`proxy headers: ${JSON.stringify(headers)}`);
  debug("stepzen:dashboard")(`proxy url: ${url}`);

  const response = await fetch(url, {
    body: JSON.stringify(req.body),
    headers: {
      ...headers,
      "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;
