// 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
// User-Agent is set explicitly so default library agents (e.g. axios) are not rejected by the gateway.

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";

async function main() {
    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
    });

    const tokenResponse = await axios.post(tokenUrl, tokenData, {
        headers: { 'User-Agent': 'Easor-API-Client/1.0' },
        timeout: 30000,
        validateStatus: () => true
    });
    if (tokenResponse.status !== 200) {
        console.error("Token request failed with HTTP", tokenResponse.status);
        console.error(tokenResponse.data);
        process.exit(1);
    }
    const accessToken = tokenResponse.data.access_token;
    console.log("This is your access token:", accessToken);

    const apiUrl = `https://apim.talenom.com/organization/v1/organization-info/${organizationNumber}`;
    const apiResponse = await axios.get(apiUrl, {
        headers: {
            'Authorization': `Bearer ${accessToken}`,
            'Content-Type': 'application/json',
            'Ocp-Apim-Subscription-Key': ocpApimSubscriptionKey,
            'User-Agent': 'Easor-API-Client/1.0'
        },
        timeout: 30000,
        validateStatus: () => true
    });
    if (apiResponse.status !== 200) {
        console.error("API request failed with HTTP", apiResponse.status);
        console.error(apiResponse.data);
        process.exit(1);
    }
    console.log("Response data:");
    console.log(apiResponse.data);
}

main().catch(error => {
    console.error("Error:", error.message);
    process.exit(1);
});