using Intentor.Models;

namespace Intentor.Services;

public class HomeAssistantService
{
    private readonly HttpClient _httpClient;
    private readonly string _supervisorToken;
    private const string SupervisorApiBase = "http://supervisor";

    public HomeAssistantService(HttpClient httpClient, string supervisorToken)
    {
        _httpClient = httpClient;
        _supervisorToken = supervisorToken;
    }

    public async Task<List<EntityState>> GetStatesAsync()
    {
        var states = await GetAsync<List<EntityState>>("core/api/states");
        return states ?? new List<EntityState>();
    }

    public async Task<T?> GetAsync<T>(string endpoint)
    {
        var response = await _httpClient.GetAsync($"{SupervisorApiBase}/{endpoint}");
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<T>();
    }

    public async Task<HttpResponseMessage> PostAsync(string endpoint, object? content = null)
    {
        var response = await _httpClient.PostAsJsonAsync($"{SupervisorApiBase}/{endpoint}", content);
        response.EnsureSuccessStatusCode();
        return response;
    }

    public async Task<T?> PostAsync<T>(string endpoint, object? content = null)
    {
        var response = await _httpClient.PostAsJsonAsync($"{SupervisorApiBase}/{endpoint}", content);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadFromJsonAsync<T>();
    }

    public async Task<HttpResponseMessage> PutAsync(string endpoint, object content)
    {
        var response = await _httpClient.PutAsJsonAsync($"{SupervisorApiBase}/{endpoint}", content);
        response.EnsureSuccessStatusCode();
        return response;
    }

    public async Task<HttpResponseMessage> DeleteAsync(string endpoint)
    {
        var response = await _httpClient.DeleteAsync($"{SupervisorApiBase}/{endpoint}");
        response.EnsureSuccessStatusCode();
        return response;
    }
}
