const axios = require("axios");
const https = require("https");

async function callSecurityScanApi(options) {
  const {
    securityScanApiBaseUrl,
    apiToken,
    allowInsecureSSL,
    payload,
    stageName
  } = options;

  const apiUrl =
    `${securityScanApiBaseUrl.replace(/\/$/, "")}/DashboardServer/v2/web/common/updateSecurityScanLastModified`;

  const headers = {
    "Content-Type": "application/json"
  };

  if (apiToken && apiToken !== "none") {
    headers["Authorization"] = `Bearer ${apiToken}`;
  }

  console.log(`========== ${stageName} REST API Call ==========`);
  console.log(`REST API Base URL : ${securityScanApiBaseUrl}`);
  console.log(`Final API URL     : ${apiUrl}`);
  console.log(`Payload           : ${JSON.stringify(payload)}`);
  console.log("================================================");

  const response = await axios.post(apiUrl, payload, {
    headers,
    httpsAgent: new https.Agent({
      rejectUnauthorized: !allowInsecureSSL
    })
  });

  console.log(`${stageName} API Response:`);
  console.log(JSON.stringify(response.data, null, 2));
}

module.exports = {
  callSecurityScanApi
};