using System.Text;
using System.Text.Json;

namespace HealthcareManagerUI.Services.Http;

public class HttpService : IHttpService
{
    public async Task<T> GetAsync<T>(string uri, IDictionary<string, string> headers = null)
    {
        using var httpClient = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Get, uri);
        AddHeaders(request, headers);

        var response = await httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<T>(
            responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
    }

    public async Task<T> GetByIdAsync<T>(string uri, int id, IDictionary<string, string> headers = null)
    {
        return await GetAsync<T>($"{uri}/{id}", headers);
    }

    public async Task<T> PostAsync<T>(string uri, object data, IDictionary<string, string> headers = null)
    {
        using var httpClient = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Post, uri);
        AddHeaders(request, headers);
        request.Content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");

        var response = await httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<T>(
            responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
    }

    public async Task<T> PutAsync<T>(string uri, int id, object data, IDictionary<string, string> headers = null)
    {
        using var httpClient = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Put, $"{uri}/{id}");
        AddHeaders(request, headers);
        request.Content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");

        var response = await httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<T>(
            responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
    }

    public async Task DeleteAsync(string uri, int id, IDictionary<string, string> headers = null)
    {
        using var httpClient = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Delete, $"{uri}/{id}");
        AddHeaders(request, headers);

        var response = await httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();
    }

    private void AddHeaders(HttpRequestMessage request, IDictionary<string, string> headers)
    {
        if (headers != null)
            foreach (var header in headers)
                request.Headers.Add(header.Key, header.Value);
    }
}