using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.Health;

namespace ZB.MOM.WW.Health.Tests;

/// <summary>
/// Verifies the canonical JSON response writer (<see cref="ZbHealthWriter.WriteJsonAsync"/>):
/// the JSON body shape, the <c>application/json</c> content type, and that the framework's
/// status-to-HTTP mapping (Healthy/Degraded → 200, Unhealthy → 503) is preserved when the
/// writer is wired onto the ready/active tiers by <see cref="ZbHealthEndpointExtensions.MapZbHealth"/>.
/// </summary>
public sealed class ResponseWriterTests
{
    private sealed class StubHealthCheck : IHealthCheck
    {
        private readonly HealthCheckResult _result;

        public StubHealthCheck(
            HealthStatus status,
            string? description = null,
            IReadOnlyDictionary<string, object>? data = null) =>
            _result = new HealthCheckResult(status, description, exception: null, data: data);

        public Task<HealthCheckResult> CheckHealthAsync(
            HealthCheckContext context,
            CancellationToken cancellationToken = default) => Task.FromResult(_result);
    }

    private static async Task<HttpResponseMessage> GetReadyAsync(
        HealthStatus status,
        string? description = "db reachable",
        IReadOnlyDictionary<string, object>? data = null)
    {
        var builder = WebApplication.CreateBuilder();
        builder.WebHost.UseTestServer();
        builder.Services.AddHealthChecks()
            .AddCheck("db", new StubHealthCheck(status, description, data), tags: new[] { ZbHealthTags.Ready });

        await using var app = builder.Build();
        app.MapZbHealth();
        await app.StartAsync();

        var client = app.GetTestClient();
        return await client.GetAsync("/health/ready");
    }

    [Fact]
    public async Task ReadyEndpoint_Healthy_WritesJsonBody_With200()
    {
        var response = await GetReadyAsync(HealthStatus.Healthy);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);

        using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
        var root = doc.RootElement;

        Assert.Equal("Healthy", root.GetProperty("status").GetString());
        Assert.Equal(JsonValueKind.Number, root.GetProperty("totalDurationMs").ValueKind);

        var entries = root.GetProperty("entries");
        var db = entries.GetProperty("db");
        Assert.Equal("Healthy", db.GetProperty("status").GetString());
        Assert.Equal("db reachable", db.GetProperty("description").GetString());
    }

    [Fact]
    public async Task ReadyEndpoint_NullDescription_EmitsDescriptionKeyAsNull()
    {
        // A check that produces no description must still emit the "description" key with a JSON null
        // value (matching the spec §3 example and the HealthChecks.UI.Client shape) rather than
        // dropping the key — so consumers can read entries.<name>.description without handling a
        // missing property.
        var response = await GetReadyAsync(HealthStatus.Healthy, description: null);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
        var db = doc.RootElement.GetProperty("entries").GetProperty("db");

        Assert.True(db.TryGetProperty("description", out var description), "description key must be present");
        Assert.Equal(JsonValueKind.Null, description.ValueKind);
    }

    [Fact]
    public async Task ReadyEndpoint_EntryWithData_EmitsDataObject_WithVerbatimKeys()
    {
        // The envelope properties are camelCased by the naming policy, but a check's own data keys are
        // dictionary keys and must survive verbatim — the dashboard reads them by exact name
        // (entries["akka-cluster"].data.leader), so a naming policy applied here would silently break
        // the contract. Values may be any JSON-friendly type (string / int / string[]).
        var data = new Dictionary<string, object>
        {
            ["leader"] = "akka.tcp://sys@node-1:4053",
            ["memberCount"] = 2,
            ["selfRoles"] = new[] { "driver", "site-a" },
        };

        var response = await GetReadyAsync(HealthStatus.Healthy, data: data);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
        var entryData = doc.RootElement.GetProperty("entries").GetProperty("db").GetProperty("data");

        Assert.Equal("akka.tcp://sys@node-1:4053", entryData.GetProperty("leader").GetString());
        Assert.Equal(2, entryData.GetProperty("memberCount").GetInt32());
        Assert.Equal(
            new[] { "driver", "site-a" },
            entryData.GetProperty("selfRoles").EnumerateArray().Select(static e => e.GetString()).ToArray());
    }

    [Fact]
    public async Task ReadyEndpoint_EntryWithoutData_OmitsDataKeyEntirely()
    {
        // The 0.2.0 non-breaking invariant: a check that publishes no data must produce exactly the
        // pre-0.2.0 body. Asserted on the raw JSON string so a `"data": null` regression (which
        // TryGetProperty would still accept as "present") fails here.
        var response = await GetReadyAsync(HealthStatus.Healthy);

        var body = await response.Content.ReadAsStringAsync();

        Assert.DoesNotContain("\"data\"", body, StringComparison.Ordinal);

        using var doc = JsonDocument.Parse(body);
        var db = doc.RootElement.GetProperty("entries").GetProperty("db");
        Assert.False(db.TryGetProperty("data", out _), "data key must be absent when the check set none");
    }

    [Fact]
    public async Task ReadyEndpoint_Degraded_Returns200_WithDegradedStatus()
    {
        var response = await GetReadyAsync(HealthStatus.Degraded);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);

        using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
        Assert.Equal("Degraded", doc.RootElement.GetProperty("status").GetString());
    }

    [Fact]
    public async Task ReadyEndpoint_Unhealthy_Returns503_WithUnhealthyStatus()
    {
        var response = await GetReadyAsync(HealthStatus.Unhealthy);

        Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
        Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);

        using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
        Assert.Equal("Unhealthy", doc.RootElement.GetProperty("status").GetString());
    }
}
