using System.Net.Http.Headers;
using e_suite.API.Common.extensions;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace e_suite.Service.EFlowSync.EflowAPI;

public class EFlowApiBase : IFlowApi
{
    protected readonly IConfiguration _configuration;

    public EFlowApiBase(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    private HttpClient? _client;
    private string _baseAddress = null!;

    protected HttpClient Client
    {
        get
        {
            if (_client == null)
            {
                _client = CreateHttpClient().GetAwaiter().GetResult();
            }
            return _client;
            
        }
    }

    private string BaseAddress
    {
        get
        {
            if (_baseAddress == null)
            {
                var eFlowServer = _configuration.GetConfigValue($"EflowAPI_SERVER", $"EflowAPI:Server", "");
                if (string.IsNullOrEmpty(eFlowServer))
                {
                    throw new Exception("EFlow Server not configured");
                }

                _baseAddress = eFlowServer;
            }

            return _baseAddress;
        }
    }

    public string ApiKey { get; set; } = string.Empty;

    private async Task<Token?> GetToken()
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(BaseAddress);
        string grant_type = "password";
        string client_id = ApiKey;

        var form = new Dictionary<string, string>
        {
            {"grant_type", grant_type},
            {"client_id", client_id}
        };

        HttpResponseMessage tokenResponse = await client.PostAsync("oauth2/token", new FormUrlEncodedContent(form));
        var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
        var token = JsonConvert.DeserializeObject<Token>(jsonContent);
        return token;
    }

    protected async Task<HttpClient> CreateHttpClient()
    {
        var token = await GetToken();
        if (token == null)
            throw new NullReferenceException("unable to get token from e-flow");

        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(BaseAddress);
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken);
        return client;
    }
}