// Copy this code and save it to a file called get-token.js
// Install dependencies with command: npm install axios copy-paste
// Run the script with command: node get-token.js
// User-Agent is set explicitly so default library agents (e.g. axios) are not rejected by the gateway.

const axios = require('axios');
const { copy } = require('copy-paste');

// Fill in your credentials below
const CLIENT_ID = "REPLACE-ME-WITH-CLIENT-ID";
const CLIENT_SECRET = "REPLACE-ME-WITH-CLIENT-SECRET";
const SCOPE = "REPLACE-ME-WITH-SCOPE";

// Get access token
axios.post("https://id.talenom.com/api/b2b/oauth2/v1.0/token",
    "grant_type=client_credentials&client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&scope=" + SCOPE,
    {
      headers: { "Content-Type": "application/x-www-form-urlencoded", "User-Agent": "Easor-API-Client/1.0" },
      timeout: 30000,
      validateStatus: () => true
    })
  .then(response => {
    if (response.status !== 200) {
      console.error("Token request failed with HTTP", response.status);
      console.error(response.data);
      process.exit(1);
    }
    const accessToken = response.data.access_token;
    console.log("Access token:", "Bearer " + accessToken);
    copy(accessToken, function(err) {
      if (err) {
        console.log("Error copying to clipboard:", err);
      } else {
        console.log("Access token also copied to your clipboard!");
      }
    });
  })
  .catch(error => {
    console.error("Error:", error.message);
    process.exit(1);
  });