using DataSharing.Share.Dtos.Province;
using IdentityModel.Client;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;

namespace DataSharing;

public class BaseHttpInvoker : IHttpInvoker, IScopeDependency
{
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly ILogger<BaseHttpInvoker> _logger;

    public BaseHttpInvoker(IHttpClientFactory httpClientFactory, ILogger<BaseHttpInvoker> logger)
    {
        _httpClientFactory = httpClientFactory;
        _logger = logger;
    }

    public async Task<TResponse?> RequestAsync<TRequest, TResponse>(
        TRequest request, Action<HttpClient>? setHttpClient = null, CancellationToken cancellationToken = default)
        where TRequest : ISharingRequest, new()
    {
        var httpClient = _httpClientFactory.CreateClient();

        if (setHttpClient != null)
            setHttpClient.Invoke(httpClient);

        var url = request.GetRequestUrl();
        var method = request.GetHttpMethod();
        var rsp = string.Empty;
        if (HttpMethods.IsGet(method))
        {
            rsp = await httpClient.GetStringAsync(url, cancellationToken);
        }
        else if (HttpMethods.IsPost(method))
        {
            using var responseMessage = await httpClient.PostAsJsonAsync(url, request, cancellationToken);
            responseMessage.EnsureSuccessStatusCode();
            using var responseContent = responseMessage.Content;
            rsp = await responseContent.ReadAsStringAsync(cancellationToken);
        }
        else
        {
            throw new UserFriendlyException("暂不支持该请求方式");
        }

        return System.Text.Json.JsonSerializer.Deserialize<TResponse>(rsp);
    }

    public async Task<TResponse?> RequestStringContentAsync<TResponse>(string url, string httpMethod, string? stringContent = null,
        Action<HttpClient>? setHttpClient = null, CancellationToken cancellationToken = default)
    {
        var httpClient = _httpClientFactory.CreateClient();
        if (setHttpClient != null)
            setHttpClient.Invoke(httpClient);
        var rsp = string.Empty;
        if (HttpMethods.IsGet(httpMethod))
        {
            rsp = await httpClient.GetStringAsync(url, cancellationToken);
        }
        else if (HttpMethods.IsPost(httpMethod))
        {
            using var responseMessage = await httpClient.PostAsync(url, new StringContent(stringContent, Encoding.UTF8, new MediaTypeWithQualityHeaderValue("application/json")),
                cancellationToken);
            responseMessage.EnsureSuccessStatusCode();
            using var responseContent = responseMessage.Content;
            rsp = await responseContent.ReadAsStringAsync(cancellationToken);
        }
        else
        {
            throw new UserFriendlyException("暂不支持该请求方式");
        }
        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };
        return JsonSerializer.Deserialize<TResponse>(rsp, options);
        //  return System.Text.Json.JsonSerializer.Deserialize<TResponse>(rsp);
    }

    public async Task<TokenResponse> GetTokenAsync(ClientCredentialsTokenRequest request, CancellationToken cancellationToken)
    {
        var httpClient = _httpClientFactory.CreateClient();
        return await httpClient.RequestClientCredentialsTokenAsync(request, cancellationToken);
    }
}