using System.Net.Http.Json;

namespace StellaOps.Scanner.WebService.Tests;

public sealed class HealthEndpointsTests
{
    [Fact]
    public async Task HealthAndReadyEndpointsRespond()
    {
        using var factory = new ScannerApplicationFactory();
        using var client = factory.CreateClient();

        var healthResponse = await client.GetAsync("/healthz");
        Assert.True(healthResponse.IsSuccessStatusCode, $"Expected 200 from /healthz, received {(int)healthResponse.StatusCode}.");

        var readyResponse = await client.GetAsync("/readyz");
        Assert.True(readyResponse.IsSuccessStatusCode, $"Expected 200 from /readyz, received {(int)readyResponse.StatusCode}.");

        var healthDocument = await healthResponse.Content.ReadFromJsonAsync<HealthDocument>();
        Assert.NotNull(healthDocument);
        Assert.Equal("healthy", healthDocument!.Status);
        Assert.True(healthDocument.UptimeSeconds >= 0);
        Assert.NotNull(healthDocument.Telemetry);

        var readyDocument = await readyResponse.Content.ReadFromJsonAsync<ReadyDocument>();
        Assert.NotNull(readyDocument);
        Assert.Equal("ready", readyDocument!.Status);
        Assert.Null(readyDocument.Error);
    }

    private sealed record HealthDocument(
        string Status,
        DateTimeOffset StartedAt,
        DateTimeOffset CapturedAt,
        double UptimeSeconds,
        TelemetryDocument Telemetry);

    private sealed record TelemetryDocument(
        bool Enabled,
        bool Logging,
        bool Metrics,
        bool Tracing);

    private sealed record ReadyDocument(
        string Status,
        DateTimeOffset CheckedAt,
        double? LatencyMs,
        string? Error);
}
