using System.Net.Http.Json;

namespace Neta.Tray;

public sealed class StatusClient(HttpClient httpClient)
{
    public async Task<RuntimeStatusDto?> GetStatusAsync(RuntimeBootstrapInfo runtime, CancellationToken cancellationToken)
    {
        using var request = new HttpRequestMessage(HttpMethod.Get, runtime.ControlBaseUrl + "/status");
        request.Headers.Add("x-neta-tray-secret", runtime.ControlSecret);
        using var response = await httpClient.SendAsync(request, cancellationToken);
        if (!response.IsSuccessStatusCode) return null;
        var envelope = await response.Content.ReadFromJsonAsync<RuntimeEnvelope>(cancellationToken: cancellationToken);
        return envelope?.Data;
    }

    public async Task StopAsync(RuntimeBootstrapInfo runtime, CancellationToken cancellationToken)
    {
        using var request = new HttpRequestMessage(HttpMethod.Post, runtime.ControlBaseUrl + "/stop");
        request.Headers.Add("x-neta-tray-secret", runtime.ControlSecret);
        using var response = await httpClient.SendAsync(request, cancellationToken);
        response.EnsureSuccessStatusCode();
    }
}

public sealed class RuntimeEnvelope
{
    public RuntimeStatusDto? Data { get; set; }
}

public sealed class RuntimeStatusDto
{
    public bool Ready { get; set; }
    public int Port { get; set; }
    public string Url { get; set; } = string.Empty;
    public string ControlBaseUrl { get; set; } = string.Empty;
}
