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>();
    }

    // Calls a HA service like scene.turn_on or script.turn_on
    public Task CallServiceAsync(string domain, string service, object data, CancellationToken ct = default)
        => PostAsync($"core/api/services/{domain}/{service}", data, ct);

    public Task ActivateSceneAsync(string sceneEntityId, CancellationToken ct = default)
        => CallServiceAsync("scene", "turn_on", new { entity_id = sceneEntityId }, ct);

    public Task RunScriptAsync(string scriptEntityId, CancellationToken ct = default)
        => CallServiceAsync("script", "turn_on", new { entity_id = scriptEntityId }, ct);

    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;
    }

    // Overload with CancellationToken (so UI can cancel / avoid hanging requests)
    public async Task<HttpResponseMessage> PostAsync(string endpoint, object? content, CancellationToken ct)
    {
        var response = await _httpClient.PostAsJsonAsync($"{SupervisorApiBase}/{endpoint}", content, ct);
        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;
    }
}
