using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using EasyPaySample.Models;

namespace EasyPaySample.Services
{
    public class EasyPayService
    {
        private readonly IConfiguration _configuration;
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;

        public EasyPayService(IConfiguration configuration, HttpClient httpClient)
        {
            _configuration = configuration;
            _httpClient = httpClient;
            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
            };
        }

        public string GetMallId() => _configuration["EasyPay:mall_id"] ?? "T5102001";
        public string GetMerchantKey() => _configuration["EasyPay:secret_key"] ?? "easypay!KICCTEST";
        public string GetBaseUrl() => _configuration["EasyPay:base_url"] ?? "https://testpgapi.easypay.co.kr";

        public async Task<EasyPayResponse?> PostAsync<T>(string endpoint, T requestData)
        {
            var url = $"{GetBaseUrl().TrimEnd('/')}/{endpoint.TrimStart('/')}";
            var json = JsonSerializer.Serialize(requestData, _jsonOptions);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await _httpClient.PostAsync(url, content);
            var responseJson = await response.Content.ReadAsStringAsync();

            return JsonSerializer.Deserialize<EasyPayResponse>(responseJson, _jsonOptions);
        }

        public string GetHmac(string data)
        {
            var key = Encoding.UTF8.GetBytes(GetMerchantKey());
            using var hmac = new HMACSHA256(key);
            var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
            return BitConverter.ToString(hash).Replace("-", "").ToLower();
        }
    }
}
