using Fw.Utility.UnifyResponse;
using RestSharp;

namespace Hotline.Api.Sdk;

public class HotlineClient : IHotlineClient, IDisposable
{
    private readonly RestClient _client;

    public HotlineClient(string baseUrl, string apiKey, string apiSecret)
    {
        var options = new RestClientOptions(baseUrl)
        {
            Authenticator = new HotlineAuthenticator(baseUrl, apiKey, apiSecret)
        };
        _client = new RestClient(options);
    }

    public async Task<ApiResponse<TResponse>> ExecuteAsync<TRequest, TResponse>(string path, Method httpMethod,
        TRequest request, CancellationToken cancellationToken)
        where TRequest : class
    {
        var req = new RestRequest(path, httpMethod);
        if (httpMethod is Method.Get)
        {
            req.AddObject(request);
        }
        else
        {
            req.AddJsonBody(request);
        }

        try
        {
            var response = await _client.ExecuteAsync<ApiResponse<TResponse>>(req, cancellationToken);
            //if (!response?.IsSuccessful ?? false)
            //    throw new HttpRequestException(
            //        $"请求热线服务失败, Code: {response.StatusCode}, Error: {response.ErrorMessage}");

            return response.Data;
        }
        catch (Exception e)
        {
            throw new HttpRequestException($"请求热线服务失败，Error: {e.Message}");
        }
    }

    public async Task<ApiResponse> ExecuteAsync<TRequest>(string path, Method httpMethod, TRequest request,
        CancellationToken cancellationToken)
        where TRequest : class
    {
        var req = new RestRequest(path, httpMethod);
        if (httpMethod is Method.Get)
        {
            req.AddObject(request);
        }
        else
        {
            req.AddJsonBody(request);
        }

        try
        {
            var response = await _client.ExecuteAsync<ApiResponse>(req, cancellationToken);
            //if (!response?.IsSuccessful ?? false)
            //    throw new HttpRequestException(
            //        $"请求热线服务失败, Code: {response.StatusCode}, Error: {response.ErrorMessage}");

            return response.Data;
        }
        catch (Exception e)
        {
            throw new HttpRequestException($"请求热线服务失败，Error: {e.Message}");
        }
    }

    /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
    public void Dispose()
    {
        _client?.Dispose();
        GC.SuppressFinalize(this);
    }
}