using System.Net;
using Fw.Utility.UnifyResponse;
using RestSharp;
using RestSharp.Authenticators;

namespace Hotline.Api.Sdk;

public class HotlineAuthenticator : AuthenticatorBase
{
    private readonly string _tokenKey = "Authorization";
    private readonly string _baseUrl;
    private readonly string _apiKey;
    private readonly string _apiSecret;

    public HotlineAuthenticator(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/v1/Identity/login/token")
        //    .AddJsonBody(new TokenRequest { Username = _apiKey, Password = _apiSecret });
        try
        {
            var response = await client.PostJsonAsync<TokenRequest, ApiResponse<string>>("api/v1/Identity/login/token",
                   new TokenRequest { Username = _apiKey, Password = _apiSecret }, cancellationToken);
            if (!response?.IsSuccess ?? false)
                throw new HttpRequestException(
                    $"热线服务授权请求失败，HttpCode: {response.Code}, Error: {response.Error}");
            var token = response?.Result;
            if (string.IsNullOrEmpty(token))
                throw new HttpRequestException("热线服务授权失败");

            if (!token.StartsWith("Bearer"))
                token = "Bearer " + token;
            return token;
            //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}");
        }

    }

    public class TokenRequest
    {
        public string Username { get; set; }

        public string Password { get; set; }
    }
}