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

namespace CashLineERP.Api.Tests;

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

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

    [Fact]
    public async Task Supplier_Statement_Delivery_Endpoints_Record_And_Acknowledge()
    {
        await _client.AuthenticateAsFinanceMakerAsync();

        var generateResponse = await _client.PostAsJsonAsync("/api/v1/finance/supplier-statements", new CreateSupplierStatementRequest(
            SupplierId: 1,
            DateFrom: new DateOnly(2026, 4, 1),
            DateTo: new DateOnly(2026, 5, 31),
            CurrencyCode: "EGP"));
        Assert.Equal(HttpStatusCode.OK, generateResponse.StatusCode);

        var statement = await generateResponse.Content.ReadFromJsonAsync<SupplierStatementResponse>();
        Assert.NotNull(statement);

        var recordResponse = await _client.PostAsJsonAsync($"/api/v1/finance/supplier-statements/{statement!.SupplierStatementId}/delivery-logs", new RecordSupplierStatementDeliveryRequest(
            DeliveredAtUtc: new DateTime(2026, 5, 31, 12, 30, 0, DateTimeKind.Utc),
            ChannelCode: "email",
            RecipientAddress: "ap@supplier.test",
            DeliveryStatusCode: "sent",
            Notes: "Statement sent by email"));
        Assert.Equal(HttpStatusCode.OK, recordResponse.StatusCode);

        var delivery = await recordResponse.Content.ReadFromJsonAsync<SupplierStatementDeliveryLogResponse>();
        Assert.NotNull(delivery);
        Assert.Equal("EMAIL", delivery!.ChannelCode);

        var acknowledgeResponse = await _client.PostAsJsonAsync($"/api/v1/finance/supplier-statement-delivery-logs/{delivery.SupplierStatementDeliveryLogId}/acknowledge", new AcknowledgeSupplierStatementDeliveryRequest(
            AcknowledgmentStatusCode: "ACKNOWLEDGED",
            Notes: "Supplier confirmed statement receipt"));
        Assert.Equal(HttpStatusCode.OK, acknowledgeResponse.StatusCode);

        var acknowledged = await acknowledgeResponse.Content.ReadFromJsonAsync<SupplierStatementDeliveryLogResponse>();
        Assert.NotNull(acknowledged);
        Assert.Equal("ACKNOWLEDGED", acknowledged!.AcknowledgmentStatusCode);

        var listResponse = await _client.GetAsync($"/api/v1/finance/supplier-statements/{statement.SupplierStatementId}/delivery-logs");
        Assert.Equal(HttpStatusCode.OK, listResponse.StatusCode);
        var logs = await listResponse.Content.ReadFromJsonAsync<List<SupplierStatementDeliveryLogResponse>>();
        Assert.NotNull(logs);
        Assert.Single(logs!);
        Assert.Equal("ACKNOWLEDGED", logs[0].AcknowledgmentStatusCode);
    }
}
