using System.Net;
using System.Net.Http.Json;
using CashLineERP.Contracts.Sales;

namespace CashLineERP.Api.Tests;

public sealed class DispatchProofOfDeliveryQaTests : IClassFixture<ApiTestFactory>
{
    private readonly HttpClient _client;

    public DispatchProofOfDeliveryQaTests(ApiTestFactory factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task Dispatch_Proof_Of_Delivery_Endpoint_Works_After_Posting()
    {
        await _client.AuthenticateAsInternalAsync();

        var postResponse = await _client.PostAsJsonAsync("/api/v1/sales/dispatches/1/post", new PostDispatchOrderRequest(
            ActorUserId: 3,
            ShippedAtUtc: new DateTime(2026, 5, 12, 8, 30, 0, DateTimeKind.Utc),
            DeliveredAtUtc: null,
            ProofOfDeliveryReceiver: null));
        Assert.Equal(HttpStatusCode.OK, postResponse.StatusCode);

        var podResponse = await _client.PostAsJsonAsync("/api/v1/sales/dispatches/1/proof-of-delivery", new RecordProofOfDeliveryRequest(
            DeliveredAtUtc: new DateTime(2026, 5, 13, 11, 0, 0, DateTimeKind.Utc),
            ProofOfDeliveryReceiver: "Warehouse Receiver",
            DeliveryConditionCode: "ACCEPTED",
            ProofOfDeliveryReference: "POD-HTTP-001",
            Notes: "Delivered and signed"));
        Assert.Equal(HttpStatusCode.OK, podResponse.StatusCode);

        var dispatch = await podResponse.Content.ReadFromJsonAsync<DispatchOrderResponse>();
        Assert.NotNull(dispatch);
        Assert.Equal("Warehouse Receiver", dispatch!.ProofOfDeliveryReceiver);
        Assert.Equal("ACCEPTED", dispatch.DeliveryConditionCode);
        Assert.Equal("POD-HTTP-001", dispatch.ProofOfDeliveryReference);
        Assert.NotNull(dispatch.ProofOfDeliveryCapturedAtUtc);
        Assert.All(dispatch.Lines, line => Assert.Equal(line.QuantityDispatched, line.QuantityDelivered));
    }
}
