// Copy this code to a file called authentication-example.js
// Make sure you have node.js installed from https://nodejs.org/
// Install axios by running:
// npm install axios
// Run the script by running:
// node authentication-example.js

const axios = require('axios');

// Fill ALL the below parameters with proper values
const clientId = "REPLACE-ME-WITH-CLIENT-ID";
const clientSecret = "REPLACE-ME-WITH-CLIENT-SECRET";
const ocpApimSubscriptionKey = "REPLACE-ME-WITH-SUBSCRIPTION-KEY";
const scope = "REPLACE-ME-WITH-SCOPE";
const organizationNumber = "REPLACE-ME-WITH-ORGANIZATION-NUMBER";

// Request new Access token. No need for changing anything below
console.log("Requesting access token from identity provider");
const tokenUrl = "https://id.talenom.com/api/b2b/oauth2/v1.0/token";
const tokenData = new URLSearchParams({
    grant_type: "client_credentials",
    client_id: clientId,
    client_secret: clientSecret,
    scope: scope
});

axios.post(tokenUrl, tokenData)
    .then(response => {
        const accessToken = response.data.access_token;
        console.log("This is your access token:", accessToken);

        // ApiUrl is the actual url to make the GET request. In this example we will call organization-api and get basic organization information.
        const apiUrl = `https://apim.talenom.com/organization/v1/organization-info/${organizationNumber}`;
        const headers = {
            'Authorization': `Bearer ${accessToken}`,
            'Content-Type': 'application/json',
            'Ocp-Apim-Subscription-Key': ocpApimSubscriptionKey
        };

        // Making the request into API
        return axios.get(apiUrl, { headers: headers });
    })
    .then(response => {
        console.log("Response data:");
        console.log(response.data);
    })
    .catch(error => {
        console.error("Error:", error.response?.data || error.message);
    });