using Microsoft.AspNetCore.Http;
using Nexus.Api.Models;
using Nexus.Api.Services;
using Xunit;

namespace Nexus.Api.Tests;

public sealed class OperationResultContractTests
{
    [Fact]
    public void FromHttpContext_UsesSafeCorrelationAndDeduplicatesAffectedRefs()
    {
        var context = new DefaultHttpContext
        {
            TraceIdentifier = "request-trace-1"
        };
        context.Request.Headers["X-Correlation-ID"] = "operation-42";
        var primary = new EntityRefDto("task", "task-1", "Primary task");

        var result = OperationResultFactory.FromHttpContext(
            context,
            "updated",
            primary,
            revision: 7,
            affectedRefs:
            [
                primary,
                new EntityRefDto("agent", "iris", "Iris"),
                new EntityRefDto("agent", "iris", "Duplicate")
            ]);

        Assert.Equal("operation-42", result.OperationId);
        Assert.Equal("operation-42", context.Response.Headers["X-Correlation-ID"]);
        Assert.Equal(7, result.Revision);
        var affected = Assert.Single(result.AffectedRefs);
        Assert.Equal("agent", affected.Type);
        Assert.Equal("iris", affected.Id);
    }

    [Fact]
    public void FromHttpContext_RejectsOversizedCallerCorrelation()
    {
        var context = new DefaultHttpContext
        {
            TraceIdentifier = "server-trace"
        };
        context.Request.Headers["X-Correlation-ID"] = new string('x', 129);

        var result = OperationResultFactory.FromHttpContext(
            context,
            "completed",
            new EntityRefDto("project", "project-1"));

        Assert.Equal("server-trace", result.OperationId);
        Assert.Equal("server-trace", context.Response.Headers["X-Correlation-ID"]);
    }
}
