
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using backstage.Models;
using NLog;
using System.Net.Http;

using System.Net.Http.Headers;
using backstage.Helpers;

namespace backstage.Helpers
{
    public interface ICallApi
    {
        Task<ResultModel> CallAPI(string url, Dictionary<string, string> parameters, HttpMethod httpMethod);


    }

    public class CallApi : ICallApi
    {

        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IConfiguration _config;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public CallApi(IHttpContextAccessor httpContextAccessor, IConfiguration config)
        {

            _config = config;
            _httpContextAccessor = httpContextAccessor;
        }
        public async Task<ResultModel> CallAPI(string url, Dictionary<string, string> parameters, HttpMethod httpMethod)
        {
            var result = new ResultModel();
            using (var handler = new HttpClientHandler())
            {
                handler.ClientCertificateOptions = ClientCertificateOption.Manual;
                handler.ServerCertificateCustomValidationCallback =
                    (httpRequestMessage, cert, certChain, policyErrors) => true;

                using (var client = new HttpClient(handler))
                {
                    try
                    {

                        // 將參數轉換為 x-www-form-urlencoded 格式
                        var content = new FormUrlEncodedContent(parameters);

                        // 建立 HttpRequestMessage 物件，設定 URL 和 HTTP 方法
                        var request = new HttpRequestMessage(httpMethod, url)
                        {
                            Content = content
                        };
                        // 計算 Content-Length
                        var contentLength = await content.ReadAsStringAsync();

                        // 取得主機名稱
                        var host = new Uri(url).Host;
                        // 設定 Content-Type 標頭
                        string token = _httpContextAccessor.HttpContext.User.FindFirstValue("token");
                        if (!string.IsNullOrEmpty(token))
                            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

                        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

                        request.Content.Headers.ContentLength = contentLength.Length;
                        //request.Headers.Host = host;
                        // 執行 API 呼叫
                        var response = await client.SendAsync(request);

                        // 檢查回應狀態碼
                        if (response.IsSuccessStatusCode)
                        {
                            // 讀取回應內容
                            result.Data = await response.Content.ReadAsStringAsync();
                            result.IsSuccess = true;
                            return result;
                        }
                        else
                        {
                            // 處理 API 呼叫失敗的情況
                            Console.WriteLine($"API 呼叫失敗：{response.StatusCode}");
                            result.Message = $"API 呼叫失敗：{response.StatusCode}";
                            return result;
                        }
                    }
                    catch (Exception ex)
                    {
                        // 處理例外情況
                        Console.WriteLine($"API 呼叫發生錯誤：{ex.Message}");
                        result.Message = $"API 呼叫失敗：{ex.Message}";
                        return result;
                    }
                }
            }
        }


    }
}
