using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;

namespace SatelliteProvider.IntegrationTests;

// AZ-796: end-to-end coverage for the inventory endpoint's strict input
// validation. Each test exercises one rule from the validator (FluentValidation
// for business rules, JsonSerializerOptions for wire-format rules) and asserts
// the response body conforms to the RFC 7807 ValidationProblemDetails contract
// in `_docs/02_document/contracts/api/error-shape.md` v1.0.0.
public static class TileInventoryValidationTests
{
    private const string InventoryPath = "/api/satellite/tiles/inventory";

    public static async Task RunAll(HttpClient httpClient)
    {
        RouteTestHelpers.PrintTestHeader("Test: Inventory endpoint strict validation (AZ-796)");

        await HappyPath_Returns200(httpClient);

        // Rule 1: body present
        await EmptyBody_Returns400(httpClient);
        // Rule 2: tiles required (one of tiles/locationHashes must be populated)
        await NeitherPopulated_Returns400(httpClient);
        await BothPopulated_Returns400(httpClient);
        // Rule 3: tiles non-empty
        await EmptyTilesArray_Returns400(httpClient);
        // Rule 4: tiles max size
        await TilesOverCap_Returns400(httpClient);
        // Rule 5: each entry has z, x, y
        await MissingZ_Returns400WithFieldPath(httpClient);
        await MissingXAndY_Returns400(httpClient);
        // Rule 6: non-negative integer fields
        await NegativeAxis_Returns400(httpClient);
        await TypeMismatch_Returns400(httpClient);
        // Rule 7: z within supported zoom range
        await ZoomOutOfRange_Returns400WithFieldPath(httpClient);
        // Rule 8: x / y within tile-axis bounds
        await XBeyondZoomBounds_Returns400(httpClient);
        await YBeyondZoomBounds_Returns400(httpClient);
        // Rule 9: unknown fields rejected
        await UnknownRootField_Returns400(httpClient);
        await UnknownNestedField_Returns400(httpClient);
        await OldV1FieldName_Returns400(httpClient);

        Console.WriteLine("✓ Inventory validation tests: PASSED");
    }

    private static async Task HappyPath_Returns200(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796: well-formed request with z/x/y triple → HTTP 200");

        // Arrange
        const string body = """{"tiles":[{"z":18,"x":1,"y":1}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);

        // Assert
        if (response.StatusCode != HttpStatusCode.OK)
        {
            var errorBody = await response.Content.ReadAsStringAsync();
            throw new Exception($"AZ-796 happy path: expected 200, got {(int)response.StatusCode}. Body: {errorBody}");
        }

        Console.WriteLine("  ✓ Valid {z, x, y} request returns HTTP 200");
    }

    private static async Task EmptyBody_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796 rule 1: empty body → HTTP 400");

        // Arrange — POST with zero-byte body and JSON content type. The framework
        // rejects the missing required body parameter before any handler/filter
        // runs, so the response is basic RFC 7807 ProblemDetails with no `errors`
        // map (vs. ValidationProblemDetails on field-level violations).
        var content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

        // Act
        var response = await httpClient.PostAsync(InventoryPath, content);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 empty body");

        // Assert
        ProblemDetailsAssertions.AssertProblemDetails(problem, expectedStatus: 400, label: "AZ-796 empty body");

        Console.WriteLine("  ✓ Empty body rejected with HTTP 400 + ProblemDetails");
    }

    private static async Task NeitherPopulated_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796 rule 2: neither tiles nor locationHashes populated → HTTP 400");

        // Arrange
        const string body = """{}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 neither populated");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(
            problem,
            expectedStatus: 400,
            label: "AZ-796 neither populated",
            expectedErrorPath: "$");

        Console.WriteLine("  ✓ Empty object rejected with errors[\"$\"] (XOR rule)");
    }

    private static async Task BothPopulated_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796 rule 2: both tiles and locationHashes populated → HTTP 400");

        // Arrange
        const string body = """{"tiles":[{"z":18,"x":1,"y":1}],"locationHashes":["00000000-0000-0000-0000-000000000000"]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 both populated");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(
            problem,
            expectedStatus: 400,
            label: "AZ-796 both populated",
            expectedErrorPath: "$");

        Console.WriteLine("  ✓ Both populated rejected with errors[\"$\"] (XOR rule)");
    }

    private static async Task EmptyTilesArray_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796 rule 3: empty tiles array → HTTP 400");

        // Arrange — XOR rule treats empty arrays as not-populated
        const string body = """{"tiles":[]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 empty tiles array");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(
            problem,
            expectedStatus: 400,
            label: "AZ-796 empty tiles array",
            expectedErrorPath: "$");

        Console.WriteLine("  ✓ Empty tiles array rejected with HTTP 400");
    }

    private static async Task TilesOverCap_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796 rule 4: > 5000 tile entries → HTTP 400");

        // Arrange — TileInventoryLimits.MaxEntriesPerRequest is 5000
        var sb = new StringBuilder();
        sb.Append("""{"tiles":[""");
        for (var i = 0; i < 5001; i++)
        {
            if (i > 0) sb.Append(',');
            sb.Append("""{"z":18,"x":1,"y":1}""");
        }
        sb.Append("]}");

        // Act
        var response = await PostJsonAsync(httpClient, sb.ToString());
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 over cap");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(
            problem,
            expectedStatus: 400,
            label: "AZ-796 over cap",
            expectedErrorPath: "tiles");

        Console.WriteLine("  ✓ 5001-entry tiles array rejected with errors[\"tiles\"]");
    }

    private static async Task MissingZ_Returns400WithFieldPath(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796: missing `z` → HTTP 400 with structured errors map");

        // Arrange — JsonRequired on TileCoord.Z catches this at the deserializer layer.
        const string body = """{"tiles":[{"x":1,"y":1}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 missing z");

        // Assert — JsonRequired surfaces parent path `tiles[0]` with static deserializer message (AZ-1113).
        ProblemDetailsAssertions.AssertValidationProblem(
            problem,
            expectedStatus: 400,
            label: "AZ-796 missing z",
            expectedErrorPath: "tiles[0]",
            expectedErrorContains: "The field value is invalid.");

        Console.WriteLine("  ✓ Missing `z` rejected with errors[\"tiles[0]\"] and sanitized message");
    }

    private static async Task MissingXAndY_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796: missing `x` and `y` → HTTP 400");

        // Arrange
        const string body = """{"tiles":[{"z":18}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 missing x/y");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(problem, expectedStatus: 400, label: "AZ-796 missing x/y");

        Console.WriteLine("  ✓ Missing `x` and `y` rejected with HTTP 400");
    }

    private static async Task ZoomOutOfRange_Returns400WithFieldPath(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796: z out of slippy-map range → HTTP 400 with errors[\"tiles[0].z\"]");

        // Arrange — z=30 is beyond the supported max of 22
        const string body = """{"tiles":[{"z":30,"x":0,"y":0}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 z=30");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(
            problem,
            expectedStatus: 400,
            label: "AZ-796 z=30",
            expectedErrorPath: "tiles[0].z",
            expectedErrorContains: "between 0 and 22");

        Console.WriteLine("  ✓ z=30 rejected with errors[\"tiles[0].z\"] mentioning range");
    }

    private static async Task XBeyondZoomBounds_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796: x ≥ 2^z → HTTP 400");

        // Arrange — at z=2, valid x is 0..3; x=4 is invalid
        const string body = """{"tiles":[{"z":2,"x":4,"y":0}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 x=4 z=2");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(
            problem,
            expectedStatus: 400,
            label: "AZ-796 x=4 z=2",
            expectedErrorPath: "tiles[0].x");

        Console.WriteLine("  ✓ x=4 at z=2 rejected with errors[\"tiles[0].x\"]");
    }

    private static async Task YBeyondZoomBounds_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796: y ≥ 2^z → HTTP 400");

        // Arrange — at z=0, valid y is 0..0; y=1 is invalid
        const string body = """{"tiles":[{"z":0,"x":0,"y":1}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 y=1 z=0");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(
            problem,
            expectedStatus: 400,
            label: "AZ-796 y=1 z=0",
            expectedErrorPath: "tiles[0].y");

        Console.WriteLine("  ✓ y=1 at z=0 rejected with errors[\"tiles[0].y\"]");
    }

    private static async Task NegativeAxis_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796: negative coordinate → HTTP 400");

        // Arrange
        const string body = """{"tiles":[{"z":18,"x":-1,"y":0}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 x=-1");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(
            problem,
            expectedStatus: 400,
            label: "AZ-796 x=-1",
            expectedErrorPath: "tiles[0].x");

        Console.WriteLine("  ✓ x=-1 rejected with errors[\"tiles[0].x\"]");
    }

    private static async Task UnknownRootField_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796: unknown root field → HTTP 400 (UnmappedMemberHandling.Disallow)");

        // Arrange
        const string body = """{"unknownField":42,"tiles":[{"z":18,"x":1,"y":1}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 unknown root field");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(problem, expectedStatus: 400, label: "AZ-796 unknown root field");
        ProblemDetailsAssertions.AssertErrorsContainsMention(problem, expectedMention: "unknownField", label: "AZ-796 unknown root field");

        Console.WriteLine("  ✓ Unknown root field rejected; errors map names the field");
    }

    private static async Task UnknownNestedField_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796: unknown nested field on tile entry → HTTP 400");

        // Arrange
        const string body = """{"tiles":[{"z":18,"x":1,"y":1,"foo":42}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 unknown nested field");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(problem, expectedStatus: 400, label: "AZ-796 unknown nested field");
        ProblemDetailsAssertions.AssertErrorsContainsMention(problem, expectedMention: "foo", label: "AZ-796 unknown nested field");

        Console.WriteLine("  ✓ Unknown nested field rejected; errors map names the field");
    }

    private static async Task OldV1FieldName_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-794 + AZ-796: legacy `tileZoom`/`tileX`/`tileY` field name → HTTP 400");

        // Arrange — exact AZ-777 Phase 1 reproduction; v1 callers must now fail explicitly
        // instead of silently coercing to (0,0,0).
        const string body = """{"tiles":[{"tileZoom":18,"tileX":1,"tileY":1}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-794 legacy field");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(problem, expectedStatus: 400, label: "AZ-794 legacy field");
        ProblemDetailsAssertions.AssertErrorsContainsMention(problem, expectedMention: "tileZoom", label: "AZ-794 legacy field");

        Console.WriteLine("  ✓ Legacy v1.x field names rejected with explicit error (no silent coercion)");
    }

    private static async Task TypeMismatch_Returns400(HttpClient httpClient)
    {
        Console.WriteLine();
        Console.WriteLine("AZ-796: type mismatch (string where integer expected) → HTTP 400");

        // Arrange
        const string body = """{"tiles":[{"z":"eighteen","x":1,"y":1}]}""";

        // Act
        var response = await PostJsonAsync(httpClient, body);
        var problem = await ProblemDetailsAssertions.ReadProblemDetailsAsync(response, "AZ-796 type mismatch");

        // Assert
        ProblemDetailsAssertions.AssertValidationProblem(problem, expectedStatus: 400, label: "AZ-796 type mismatch");

        Console.WriteLine("  ✓ String-where-int rejected with HTTP 400");
    }

    private static Task<HttpResponseMessage> PostJsonAsync(HttpClient httpClient, string body)
    {
        var content = new StringContent(body, Encoding.UTF8, "application/json");
        return httpClient.PostAsync(InventoryPath, content);
    }
}
