namespace PanoptesFrontend.Services;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using  System.Threading.Tasks;
using System.Text.Json;

public interface IHttpService
{
    Task<T> GetAsync<T>(string endpoint);
    Task<HttpStatusCode> PostAsync(string endpoint, object value);
}

public class HttpService : IHttpService {

    private readonly HttpClient httpClient;

    public HttpService(HttpClient httpClient){
        this.httpClient = httpClient;
    }

    public async Task<T> GetAsync<T>(string endpoint){
        var response = await httpClient.GetAsync(endpoint);
        
        if (response.IsSuccessStatusCode){
            var contentStream = await response.Content.ReadAsStreamAsync();
            var options = new JsonSerializerOptions {PropertyNameCaseInsensitive = true};
            return await JsonSerializer.DeserializeAsync<T>(contentStream, options);
        }
        else {
            throw new Exception($"Failed to get data from endpoint: {endpoint}. Error code: {response.StatusCode}");
        }
    }

    public async Task<HttpStatusCode> PostAsync(string endpoint, object value){
        var request = await httpClient.PostAsJsonAsync(endpoint, value);

        request.EnsureSuccessStatusCode();

        return request.StatusCode;
    }
}