using RestSharp;
using RestSharp.Authenticators;

namespace Tr.Sdk;

public class TrAuthenticator : AuthenticatorBase
{
    private readonly string _tokenKey = "X-Auth-Token";
    private readonly string _baseUrl;
    private readonly string _apiKey;
    private readonly string _apiSecret;

    public TrAuthenticator(string baseUrl, string apiKey, string apiSecret) : base("")
    {
        _baseUrl = baseUrl;
        _apiKey = apiKey;
        _apiSecret = apiSecret;
    }

    protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken)
    {
        if (string.IsNullOrEmpty(Token))
        {
            Token = await GetTokenAsync(default);
        }
        return new HeaderParameter(_tokenKey, Token);
    }

    public async Task<string> GetTokenAsync(CancellationToken cancellationToken)
    {
        var options = new RestClientOptions(_baseUrl);
        using var client = new RestClient(options);
        var request = new RestRequest("api/login")
            .AddObject(new { username = _apiKey, password = _apiSecret });
        try
        {
            var response = await client.GetAsync(request, cancellationToken);
            if (!response.IsSuccessful)
                throw new HttpRequestException(
                    $"呼叫中心服务授权请求失败，HttpCode: {response.StatusCode}, Error: {response.ErrorMessage}");
            var token = response.Headers?.FirstOrDefault(d => d.Name == _tokenKey);
            if (token is null)
                throw new HttpRequestException("呼叫中心服务授权失败");
            if (token?.Value is null)
                throw new HttpRequestException("呼叫中心token无效");

            return token.Value.ToString();
        }
        catch (Exception e)
        {
            throw new HttpRequestException($"呼叫中心授权请求失败，Error: {e.Message}");
        }

    }
}