// Create new project with command: dotnet new console -n AuthExample
// cd into the project directory: cd AuthExample
// Copy this code and replace the created Program.cs with it
// Install package: dotnet add package Newtonsoft.Json
// Replace the placeholders with your credentials
// Run with command: dotnet run

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

class Program
{
    static async Task Main(string[] args)
    {
        // Fill in your credentials below
        var clientId = "REPLACE-ME-WITH-CLIENT-ID";
        var clientSecret = "REPLACE-ME-WITH-CLIENT-SECRET";
        var scope = "REPLACE-ME-WITH-SCOPE";
        var subscriptionKey = "REPLACE-ME-WITH-SUBSCRIPTION-KEY";
        var organizationNumber = "REPLACE-ME-WITH-ORGANIZATION-NUMBER";

        // Request new Access token. No need for changing anything below
        Console.WriteLine("Requesting access token from identity provider");
        var tokenUrl = "https://id.talenom.com/api/b2b/oauth2/v1.0/token";
        
        using (var client = new HttpClient())
        {
            var tokenData = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair("grant_type", "client_credentials"),
                new KeyValuePair("client_id", clientId),
                new KeyValuePair("client_secret", clientSecret),
                new KeyValuePair("scope", scope)
            });

            var tokenResponse = await client.PostAsync(tokenUrl, tokenData);
            var tokenContent = await tokenResponse.Content.ReadAsStringAsync();
            var tokenJson = JObject.Parse(tokenContent);
            var accessToken = tokenJson["access_token"].ToString();
            Console.WriteLine("This is your access token: " + accessToken);

            // ApiUrl is the actual url to make the GET request
            var apiUrl = $"https://apim.talenom.com/organization/v1/organization-info/{organizationNumber}";
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

            // Making the request into API
            var apiResponse = await client.GetAsync(apiUrl);
            var apiContent = await apiResponse.Content.ReadAsStringAsync();
            Console.WriteLine("Response data:");
            Console.WriteLine(apiContent);
        }
    }
}