using System.Net;
using System.Net.Http.Json;
using CashLineERP.Application.Finance;
using CashLineERP.Application.Integration;
using CashLineERP.Application.Tax;
using CashLineERP.Contracts.Finance;
using CashLineERP.Contracts.Integration;
using CashLineERP.Contracts.Tax;
using CashLineERP.Infrastructure.Persistence;
using Microsoft.Extensions.DependencyInjection;

namespace CashLineERP.Api.Tests;

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

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

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

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA auth endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/connect/token",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-client|eta-secret");

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA submit endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/api/v1.0/transport/documentsubmissions",
            authenticationModeCode: "BEARER",
            credentialReference: null);

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA submission status endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "GET",
            relativePath: "/api/v1.0/submissions",
            authenticationModeCode: "BEARER",
            credentialReference: null);

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA callback ping endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/eta/ping",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-ping-secret");

        var response = await _client.GetAsync("/api/v1/integrations/eta/auth/health");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var payload = await response.Content.ReadFromJsonAsync<EtaAuthorityAuthHealthResponse>();
        Assert.NotNull(payload);
        Assert.True(payload!.AuthEndpointConfigured);
        Assert.True(payload.SubmissionEndpointConfigured);
        Assert.True(payload.SubmissionStatusEndpointConfigured);
        Assert.True(payload.CallbackPingEndpointConfigured);
        Assert.True(payload.CredentialsResolved);
        Assert.True(payload.ReadyForLiveAuth);
        Assert.Equal("READY_FOR_AUTH", payload.StatusCode);
    }

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

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA auth endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/connect/token",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-client|eta-secret");

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA submit endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/api/v1.0/documentsubmissions",
            authenticationModeCode: "BEARER",
            credentialReference: null);

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA submission status endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "GET",
            relativePath: "/api/v1.0/submissions",
            authenticationModeCode: "BEARER",
            credentialReference: null);

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        var response = await _client.GetAsync("/api/v1/integrations/eta/auth/health");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var payload = await response.Content.ReadFromJsonAsync<EtaAuthorityAuthHealthResponse>();
        Assert.NotNull(payload);
        Assert.False(payload!.CallbackPingEndpointConfigured);
        Assert.Null(payload.CallbackPingEndpointCode);
        Assert.True(payload.ReadyForLiveAuth);
    }

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

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA callback ping endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/eta/ping",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-ping-secret");

        _client.DefaultRequestHeaders.Authorization = null;

        using var response = await _client.PutAsync("/api/v1/integrations/eta/ping?token=eta-ping-secret&echo=eta-hello", new StringContent(string.Empty));
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var payload = await response.Content.ReadFromJsonAsync<EtaAuthorityPingResponse>();
        Assert.NotNull(payload);
        Assert.True(payload!.Verified);
        Assert.Equal("VERIFIED", payload.StatusCode);
        Assert.Equal("eta-hello", payload.EchoText);
    }

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

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA UAT auth endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/connect/token",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://uat-client|uat-secret",
            environmentCode: "UAT");

        var certAuthEndpoint = await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA CERT auth endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/connect/token",
            authenticationModeCode: "BASIC",
            credentialReference: "secret://eta/cert/client-id|eta/cert/client-secret",
            environmentCode: "CERT");

        const string targetEnvironmentVariable = "EtaAuthority__TargetEnvironmentCode";
        const string clientIdVariable = "SecretReferences__ETA__CERT__CLIENT_ID";
        const string clientSecretVariable = "SecretReferences__ETA__CERT__CLIENT_SECRET";
        var originalTargetEnvironment = Environment.GetEnvironmentVariable(targetEnvironmentVariable);
        var originalClientId = Environment.GetEnvironmentVariable(clientIdVariable);
        var originalClientSecret = Environment.GetEnvironmentVariable(clientSecretVariable);

        try
        {
            Environment.SetEnvironmentVariable(targetEnvironmentVariable, "CERT");
            Environment.SetEnvironmentVariable(clientIdVariable, "cert-client");
            Environment.SetEnvironmentVariable(clientSecretVariable, "cert-secret");

            using var scope = _factory.Services.CreateScope();
            var integrationEndpointRegistryService = scope.ServiceProvider.GetRequiredService<IIntegrationEndpointRegistryService>();
            var authService = new EtaAuthorityAuthService(integrationEndpointRegistryService);
            var health = authService.GetHealth();

            Assert.True(health.AuthEndpointConfigured);
            Assert.True(health.CredentialsResolved);
            Assert.Equal("READY_FOR_AUTH", health.StatusCode);
            Assert.Equal(certAuthEndpoint.EndpointCode, health.AuthEndpointCode);
        }
        finally
        {
            Environment.SetEnvironmentVariable(targetEnvironmentVariable, originalTargetEnvironment);
            Environment.SetEnvironmentVariable(clientIdVariable, originalClientId);
            Environment.SetEnvironmentVariable(clientSecretVariable, originalClientSecret);
        }
    }

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

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA CERT callback ping endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1/integrations/eta/ping",
            authenticationModeCode: "API_KEY",
            credentialReference: "secret://eta/cert/ping-secret",
            environmentCode: "CERT");

        const string targetEnvironmentVariable = "EtaAuthority__TargetEnvironmentCode";
        const string pingSecretVariable = "SecretReferences__ETA__CERT__PING_SECRET";
        var originalTargetEnvironment = Environment.GetEnvironmentVariable(targetEnvironmentVariable);
        var originalPingSecret = Environment.GetEnvironmentVariable(pingSecretVariable);

        try
        {
            Environment.SetEnvironmentVariable(targetEnvironmentVariable, "CERT");
            Environment.SetEnvironmentVariable(pingSecretVariable, "cert-ping-secret");

            using var scope = _factory.Services.CreateScope();
            var integrationEndpointRegistryService = scope.ServiceProvider.GetRequiredService<IIntegrationEndpointRegistryService>();
            var authService = new EtaAuthorityAuthService(integrationEndpointRegistryService);
            var sharedSecret = authService.ResolveCallbackPingSharedSecret();

            Assert.Equal("cert-ping-secret", sharedSecret);
        }
        finally
        {
            Environment.SetEnvironmentVariable(targetEnvironmentVariable, originalTargetEnvironment);
            Environment.SetEnvironmentVariable(pingSecretVariable, originalPingSecret);
        }
    }

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

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        _client.DefaultRequestHeaders.Authorization = null;

        const string payloadText = """
        {
          "notificationId": "ETA-NOTIF-001",
          "type": "DocumentReceived",
          "notifications": [
            {
              "submissionUUID": "SUB-ETA-001",
              "documentUUID": "DOC-ETA-001"
            }
          ]
        }
        """;

        using var callbackRequest = new HttpRequestMessage(HttpMethod.Put, "/api/v1/integrations/eta/notifications/documents");
        callbackRequest.Headers.TryAddWithoutValidation("Authorization", "ApiKey eta-callback-secret");
        callbackRequest.Content = new StringContent(payloadText, System.Text.Encoding.UTF8, "application/json");

        using var callbackResponse = await _client.SendAsync(callbackRequest);
        Assert.Equal(HttpStatusCode.OK, callbackResponse.StatusCode);

        var callbackPayload = await callbackResponse.Content.ReadFromJsonAsync<EtaDocumentNotificationReceiptResponse>();
        Assert.NotNull(callbackPayload);
        Assert.True(callbackPayload!.Accepted);
        Assert.False(callbackPayload.Reconciled);
        Assert.NotNull(callbackPayload.InboxMessageId);
        Assert.Equal("ETA-NOTIF-001", callbackPayload.ExternalMessageId);
        Assert.Equal("SUB-ETA-001", callbackPayload.CorrelationKey);

        await _client.AuthenticateAsInternalAsync();
        var inboxResponse = await _client.GetAsync("/api/v1/integrations/inbox?integrationProviderCode=ETA");
        Assert.Equal(HttpStatusCode.OK, inboxResponse.StatusCode);
        var inboxItems = await inboxResponse.Content.ReadFromJsonAsync<InboxMessageResponse[]>();
        Assert.NotNull(inboxItems);
        Assert.Contains(inboxItems!, item => item.InboxMessageId == callbackPayload.InboxMessageId && item.CorrelationKey == "SUB-ETA-001");
    }

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

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        _client.DefaultRequestHeaders.Authorization = null;

        const string payloadText = """
        {
          "notificationId": "ETA-NOTIF-IDEMP-001",
          "type": "DocumentReceived",
          "notifications": [
            {
              "submissionUUID": "SUB-ETA-IDEMP-001",
              "documentUUID": "DOC-ETA-IDEMP-001"
            }
          ]
        }
        """;

        using var firstRequest = new HttpRequestMessage(HttpMethod.Put, "/api/v1/integrations/eta/notifications/documents");
        firstRequest.Headers.TryAddWithoutValidation("Authorization", "ApiKey eta-callback-secret");
        firstRequest.Content = new StringContent(payloadText, System.Text.Encoding.UTF8, "application/json");
        using var firstResponse = await _client.SendAsync(firstRequest);
        Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
        var firstPayload = await firstResponse.Content.ReadFromJsonAsync<EtaDocumentNotificationReceiptResponse>();
        Assert.NotNull(firstPayload);
        Assert.Equal("ACCEPTED", firstPayload!.StatusCode);

        using var secondRequest = new HttpRequestMessage(HttpMethod.Put, "/api/v1/integrations/eta/notifications/documents");
        secondRequest.Headers.TryAddWithoutValidation("Authorization", "ApiKey eta-callback-secret");
        secondRequest.Content = new StringContent(payloadText, System.Text.Encoding.UTF8, "application/json");
        using var secondResponse = await _client.SendAsync(secondRequest);
        Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
        var secondPayload = await secondResponse.Content.ReadFromJsonAsync<EtaDocumentNotificationReceiptResponse>();
        Assert.NotNull(secondPayload);
        Assert.True(secondPayload!.Accepted);
        Assert.Equal("IDEMPOTENT_REPLAY", secondPayload.StatusCode);
        Assert.Equal(firstPayload.InboxMessageId, secondPayload.InboxMessageId);
    }

    [Fact]
    public async Task Eta_Document_Notification_Callback_Reconciles_Accepted_Transmission()
    {
        await ResetEtaEndpointStateAsync();
        var invoiceId = CreatePostedEtaInvoice();

        await _client.AuthenticateAsInternalAsync();
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA outbound transport endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/api/v1.0/documentsubmissions/transport",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-signing-secret");
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        await _client.AuthenticateAsFinanceMakerAsync();
        var submitResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submit",
            new SubmitInvoiceToEtaRequest(ActorUserId: 0, PayloadText: null));
        Assert.Equal(HttpStatusCode.OK, submitResponse.StatusCode);
        var submission = await submitResponse.Content.ReadFromJsonAsync<EtaSubmissionLogResponse>();
        Assert.NotNull(submission);

        var linkedResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission!.EtaSubmissionLogId}/response",
            new RecordEtaInvoiceResponseRequest(
                ActorUserId: 0,
                StatusCode: "SUBMITTED",
                EtaUuid: null,
                ResponseText: "{\"authoritySubmissionUuid\":\"SUB-CALLBACK-ACPT-001\"}",
                ErrorCode: null,
                ErrorMessage: null,
                NotesText: "Linked to ETA authority submission UUID for callback reconciliation."));
        Assert.Equal(HttpStatusCode.OK, linkedResponse.StatusCode);

        var queueResponse = await _client.PostAsync($"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission.EtaSubmissionLogId}/queue-transmission", null);
        Assert.Equal(HttpStatusCode.OK, queueResponse.StatusCode);

        var dispatchResult = DispatchEtaBatch();
        var transmission = Assert.Single(dispatchResult.Transmissions);

        _client.DefaultRequestHeaders.Authorization = null;
        const string payloadText = """
        {
          "notificationId": "ETA-NOTIF-ACPT-001",
          "type": "DocumentReceived",
          "notifications": [
            {
              "submissionUUID": "SUB-CALLBACK-ACPT-001",
              "documentUUID": "ETA-DOC-ACPT-001",
              "status": "Valid"
            }
          ]
        }
        """;

        using var callbackRequest = new HttpRequestMessage(HttpMethod.Put, "/api/v1/integrations/eta/notifications/documents");
        callbackRequest.Headers.TryAddWithoutValidation("Authorization", "ApiKey eta-callback-secret");
        callbackRequest.Content = new StringContent(payloadText, System.Text.Encoding.UTF8, "application/json");

        using var callbackResponse = await _client.SendAsync(callbackRequest);
        Assert.Equal(HttpStatusCode.OK, callbackResponse.StatusCode);

        var callbackPayload = await callbackResponse.Content.ReadFromJsonAsync<EtaDocumentNotificationReceiptResponse>();
        Assert.NotNull(callbackPayload);
        Assert.True(callbackPayload!.Accepted);
        Assert.True(callbackPayload.Reconciled);
        Assert.Equal(transmission.EtaTransmissionAttemptId, callbackPayload.ReconciledTransmissionId);
        Assert.Equal("ACCEPTED", callbackPayload.ReconciliationOutcome);

        var transmissionDetail = GetTransmission(transmission.EtaTransmissionAttemptId);
        Assert.NotNull(transmissionDetail);
        Assert.Equal("ACCEPTED", transmissionDetail!.StatusCode);
    }

    [Fact]
    public async Task Eta_Document_Notification_Callback_Infers_Accepted_Status_From_DocumentReceived_Message_Type()
    {
        await ResetEtaEndpointStateAsync();
        var invoiceId = CreatePostedEtaInvoice();

        await _client.AuthenticateAsInternalAsync();
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA outbound transport endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/api/v1.0/documentsubmissions/transport",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-signing-secret");
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        await _client.AuthenticateAsFinanceMakerAsync();
        var submitResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submit",
            new SubmitInvoiceToEtaRequest(ActorUserId: 0, PayloadText: null));
        var submission = await submitResponse.Content.ReadFromJsonAsync<EtaSubmissionLogResponse>();
        Assert.NotNull(submission);

        await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission!.EtaSubmissionLogId}/response",
            new RecordEtaInvoiceResponseRequest(
                ActorUserId: 0,
                StatusCode: "SUBMITTED",
                EtaUuid: null,
                ResponseText: "{\"authoritySubmissionUuid\":\"SUB-CALLBACK-INFER-001\"}",
                ErrorCode: null,
                ErrorMessage: null,
                NotesText: "Linked to ETA authority submission UUID for message-type inference."));
        await _client.PostAsync($"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission.EtaSubmissionLogId}/queue-transmission", null);

        var dispatchResult = DispatchEtaBatch();
        var transmission = Assert.Single(dispatchResult.Transmissions);

        _client.DefaultRequestHeaders.Authorization = null;
        const string payloadText = """
        {
          "notificationId": "ETA-NOTIF-INFER-001",
          "type": "DocumentReceived",
          "notifications": [
            {
              "submissionUUID": "SUB-CALLBACK-INFER-001",
              "documentUUID": "ETA-DOC-INFER-001"
            }
          ]
        }
        """;

        using var callbackRequest = new HttpRequestMessage(HttpMethod.Put, "/api/v1/integrations/eta/notifications/documents");
        callbackRequest.Headers.TryAddWithoutValidation("Authorization", "ApiKey eta-callback-secret");
        callbackRequest.Content = new StringContent(payloadText, System.Text.Encoding.UTF8, "application/json");

        using var callbackResponse = await _client.SendAsync(callbackRequest);
        Assert.Equal(HttpStatusCode.OK, callbackResponse.StatusCode);

        var callbackPayload = await callbackResponse.Content.ReadFromJsonAsync<EtaDocumentNotificationReceiptResponse>();
        Assert.NotNull(callbackPayload);
        Assert.True(callbackPayload!.Accepted);
        Assert.True(callbackPayload.Reconciled);
        Assert.Equal(transmission.EtaTransmissionAttemptId, callbackPayload.ReconciledTransmissionId);
        Assert.Equal("ACCEPTED", callbackPayload.ReconciliationOutcome);

        await _client.AuthenticateAsFinanceCheckerAsync();
        var queueResponse = await _client.GetAsync("/api/v1/finance/eta-notifications?statusCode=RECEIVED");
        var queueItems = await queueResponse.Content.ReadFromJsonAsync<InboxMessageResponse[]>();
        Assert.NotNull(queueItems);
        Assert.DoesNotContain(queueItems!, item => item.ExternalMessageId == "ETA-NOTIF-INFER-001");

        var transmissionDetail = GetTransmission(transmission.EtaTransmissionAttemptId);
        Assert.NotNull(transmissionDetail);
        Assert.Equal("ACCEPTED", transmissionDetail!.StatusCode);
    }

    [Fact]
    public async Task Eta_Document_Notification_Callback_Reconciles_Rejected_Transmission_With_Error_Mapping()
    {
        await ResetEtaEndpointStateAsync();
        var invoiceId = CreatePostedEtaInvoice();

        await _client.AuthenticateAsInternalAsync();
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA outbound transport endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/api/v1.0/transport/documentsubmissions",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-signing-secret");
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        await _client.AuthenticateAsFinanceMakerAsync();
        var submitResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submit",
            new SubmitInvoiceToEtaRequest(ActorUserId: 0, PayloadText: null));
        Assert.Equal(HttpStatusCode.OK, submitResponse.StatusCode);
        var submission = await submitResponse.Content.ReadFromJsonAsync<EtaSubmissionLogResponse>();
        Assert.NotNull(submission);

        var linkedResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission!.EtaSubmissionLogId}/response",
            new RecordEtaInvoiceResponseRequest(
                ActorUserId: 0,
                StatusCode: "SUBMITTED",
                EtaUuid: null,
                ResponseText: "{\"authoritySubmissionUuid\":\"SUB-CALLBACK-REJ-001\"}",
                ErrorCode: null,
                ErrorMessage: null,
                NotesText: "Linked to ETA authority submission UUID for callback reconciliation."));
        Assert.Equal(HttpStatusCode.OK, linkedResponse.StatusCode);

        var queueResponse = await _client.PostAsync($"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission.EtaSubmissionLogId}/queue-transmission", null);
        Assert.Equal(HttpStatusCode.OK, queueResponse.StatusCode);

        var dispatchResult = DispatchEtaBatch();
        var transmission = Assert.Single(dispatchResult.Transmissions);

        _client.DefaultRequestHeaders.Authorization = null;
        const string payloadText = """
        {
          "notificationId": "ETA-NOTIF-REJ-001",
          "type": "DocumentRejected",
          "notifications": [
            {
              "submissionUUID": "SUB-CALLBACK-REJ-001",
              "documentUUID": "ETA-DOC-REJ-001",
              "status": "Rejected",
              "errors": [
                {
                  "code": "CF440",
                  "message": "Buyer tax identifier is invalid."
                }
              ]
            }
          ]
        }
        """;

        using var callbackRequest = new HttpRequestMessage(HttpMethod.Put, "/api/v1/integrations/eta/notifications/documents");
        callbackRequest.Headers.TryAddWithoutValidation("Authorization", "ApiKey eta-callback-secret");
        callbackRequest.Content = new StringContent(payloadText, System.Text.Encoding.UTF8, "application/json");

        using var callbackResponse = await _client.SendAsync(callbackRequest);
        Assert.Equal(HttpStatusCode.OK, callbackResponse.StatusCode);

        var callbackPayload = await callbackResponse.Content.ReadFromJsonAsync<EtaDocumentNotificationReceiptResponse>();
        Assert.NotNull(callbackPayload);
        Assert.True(callbackPayload!.Accepted);
        Assert.True(callbackPayload.Reconciled);
        Assert.Equal(transmission.EtaTransmissionAttemptId, callbackPayload.ReconciledTransmissionId);
        Assert.Equal("REJECTED", callbackPayload.ReconciliationOutcome);
        Assert.Equal("CF440", callbackPayload.ReconciliationErrorCode);
        Assert.Equal("Buyer tax identifier is invalid.", callbackPayload.ReconciliationErrorMessage);

        var transmissionDetail = GetTransmission(transmission.EtaTransmissionAttemptId);
        Assert.NotNull(transmissionDetail);
        Assert.Equal("REJECTED", transmissionDetail!.StatusCode);
        Assert.Equal("Buyer tax identifier is invalid.", transmissionDetail.LastErrorText);
    }

    [Fact]
    public async Task Eta_Notification_Batch_Processes_Pending_Inbox_And_Reconciles_Transmission()
    {
        await ResetEtaEndpointStateAsync();
        var invoiceId = CreatePostedEtaInvoice();

        await _client.AuthenticateAsInternalAsync();
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA outbound transport endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/api/v1.0/transport/documentsubmissions",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-signing-secret");
        var inboundEndpoint = await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        await _client.AuthenticateAsFinanceMakerAsync();
        var submitResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submit",
            new SubmitInvoiceToEtaRequest(ActorUserId: 0, PayloadText: null));
        var submission = await submitResponse.Content.ReadFromJsonAsync<EtaSubmissionLogResponse>();
        Assert.NotNull(submission);
        await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission!.EtaSubmissionLogId}/response",
            new RecordEtaInvoiceResponseRequest(
                ActorUserId: 0,
                StatusCode: "SUBMITTED",
                EtaUuid: null,
                ResponseText: "{\"authoritySubmissionUuid\":\"SUB-WORKER-ETA-001\"}",
                ErrorCode: null,
                ErrorMessage: null,
                NotesText: "Linked for worker reconciliation."));
        await _client.PostAsync($"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission.EtaSubmissionLogId}/queue-transmission", null);

        var dispatchResult = DispatchEtaBatch();
        var transmission = Assert.Single(dispatchResult.Transmissions);

        using (var scope = _factory.Services.CreateScope())
        {
            var inboxService = scope.ServiceProvider.GetRequiredService<IInboxMessageService>();
            inboxService.ReceiveInboxMessage(1, new ReceiveInboxMessageRequest(
                inboundEndpoint.IntegrationEndpointId,
                "DOCUMENTRECEIVED",
                "ETA-NOTIF-WORKER-001",
                "SUB-WORKER-ETA-001",
                """
                {
                  "notificationId": "ETA-NOTIF-WORKER-001",
                  "type": "DocumentReceived",
                  "notifications": [
                    {
                      "submissionUUID": "SUB-WORKER-ETA-001",
                      "documentUUID": "ETA-DOC-WORKER-001",
                      "status": "Valid"
                    }
                  ]
                }
                """));
        }

        using (var scope = _factory.Services.CreateScope())
        {
            var callbackService = scope.ServiceProvider.GetRequiredService<IEtaAuthorityCallbackService>();
            var result = callbackService.ProcessPendingNotifications(new ProcessEtaDocumentNotificationBatchRequest("ETA_NOTIFY_TEST", 10));
            Assert.Equal(1, result.ProcessedCount);
            Assert.Equal(1, result.ReconciledCount);
            Assert.Single(result.ProcessedInboxMessageIds);
            Assert.Single(result.ReconciledTransmissionIds);
        }

        var transmissionDetail = GetTransmission(transmission.EtaTransmissionAttemptId);
        Assert.NotNull(transmissionDetail);
        Assert.Equal("ACCEPTED", transmissionDetail!.StatusCode);
    }

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

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        _client.DefaultRequestHeaders.Authorization = null;
        using (var callbackRequest = new HttpRequestMessage(HttpMethod.Put, "/api/v1/integrations/eta/notifications/documents"))
        {
            callbackRequest.Headers.TryAddWithoutValidation("Authorization", "ApiKey eta-callback-secret");
            callbackRequest.Content = new StringContent(
                """
                {
                  "notificationId": "ETA-NOTIF-OPS-001",
                  "type": "DocumentReceived",
                  "notifications": [
                    {
                      "submissionUUID": "SUB-ETA-OPS-001",
                      "documentUUID": "DOC-ETA-OPS-001"
                    }
                  ]
                }
                """,
                System.Text.Encoding.UTF8,
                "application/json");

            using var callbackResponse = await _client.SendAsync(callbackRequest);
            Assert.Equal(HttpStatusCode.OK, callbackResponse.StatusCode);
        }

        await _client.AuthenticateAsFinanceCheckerAsync();

        var queueResponse = await _client.GetAsync("/api/v1/finance/eta-notifications?statusCode=RECEIVED");
        Assert.Equal(HttpStatusCode.OK, queueResponse.StatusCode);
        var queueItems = await queueResponse.Content.ReadFromJsonAsync<InboxMessageResponse[]>();
        Assert.NotNull(queueItems);
        Assert.Contains(queueItems!, item => item.ExternalMessageId == "ETA-NOTIF-OPS-001" && item.StatusCode == "RECEIVED");

        var monitoringResponse = await _client.GetAsync("/api/v1/finance/eta-notifications/monitoring?itemLimit=5");
        Assert.Equal(HttpStatusCode.OK, monitoringResponse.StatusCode);
        var monitoring = await monitoringResponse.Content.ReadFromJsonAsync<EtaNotificationMonitoringResponse>();
        Assert.NotNull(monitoring);
        Assert.True(monitoring!.ReceivedNotificationCount >= 1);
        Assert.Contains(monitoring.RecentNotifications, item => item.ExternalMessageId == "ETA-NOTIF-OPS-001");
    }

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

        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        _client.DefaultRequestHeaders.Authorization = null;
        using (var callbackRequest = new HttpRequestMessage(HttpMethod.Put, "/api/v1/integrations/eta/notifications/documents"))
        {
            callbackRequest.Headers.TryAddWithoutValidation("Authorization", "ApiKey eta-callback-secret");
            callbackRequest.Content = new StringContent(
                """
                {
                  "notificationId": "ETA-NOTIF-SUPPORT-001",
                  "type": "DocumentReceived",
                  "notifications": [
                    {
                      "submissionUUID": "SUB-ETA-SUPPORT-001",
                      "documentUUID": "DOC-ETA-SUPPORT-001"
                    }
                  ]
                }
                """,
                System.Text.Encoding.UTF8,
                "application/json");

            using var callbackResponse = await _client.SendAsync(callbackRequest);
            Assert.Equal(HttpStatusCode.OK, callbackResponse.StatusCode);
        }

        await _client.AuthenticateAsInternalAsync();
        var queueResponse = await _client.GetAsync("/api/v1/finance/eta-notifications?statusCode=RECEIVED");
        Assert.Equal(HttpStatusCode.OK, queueResponse.StatusCode);

        var monitoringResponse = await _client.GetAsync("/api/v1/finance/eta-notifications/monitoring?itemLimit=5");
        Assert.Equal(HttpStatusCode.OK, monitoringResponse.StatusCode);
    }

    [Fact]
    public async Task Eta_Notification_Reprocess_Endpoint_Reconciles_Pending_Transmission()
    {
        await ResetEtaEndpointStateAsync();
        var invoiceId = CreatePostedEtaInvoice();

        await _client.AuthenticateAsInternalAsync();
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA outbound transport endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/api/v1.0/transport/documentsubmissions",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-signing-secret");
        var inboundEndpoint = await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        await _client.AuthenticateAsFinanceMakerAsync();
        var submitResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submit",
            new SubmitInvoiceToEtaRequest(ActorUserId: 0, PayloadText: null));
        var submission = await submitResponse.Content.ReadFromJsonAsync<EtaSubmissionLogResponse>();
        Assert.NotNull(submission);
        await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission!.EtaSubmissionLogId}/response",
            new RecordEtaInvoiceResponseRequest(
                ActorUserId: 0,
                StatusCode: "SUBMITTED",
                EtaUuid: null,
                ResponseText: "{\"authoritySubmissionUuid\":\"SUB-ETA-REPROCESS-001\"}",
                ErrorCode: null,
                ErrorMessage: null,
                NotesText: "Linked for ETA support reprocess."));
        await _client.PostAsync($"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission.EtaSubmissionLogId}/queue-transmission", null);

        var dispatchResult = DispatchEtaBatch();
        var transmission = Assert.Single(dispatchResult.Transmissions);

        long inboxMessageId;
        using (var scope = _factory.Services.CreateScope())
        {
            var inboxService = scope.ServiceProvider.GetRequiredService<IInboxMessageService>();
            inboxMessageId = inboxService.ReceiveInboxMessage(1, new ReceiveInboxMessageRequest(
                inboundEndpoint.IntegrationEndpointId,
                "DOCUMENTRECEIVED",
                "ETA-NOTIF-REPROCESS-001",
                "SUB-ETA-REPROCESS-001",
                """
                {
                  "notificationId": "ETA-NOTIF-REPROCESS-001",
                  "type": "DocumentReceived",
                  "notifications": [
                    {
                      "submissionUUID": "SUB-ETA-REPROCESS-001",
                      "documentUUID": "ETA-DOC-REPROCESS-001",
                      "status": "Valid"
                    }
                  ]
                }
                """)).InboxMessageId;
        }

        await _client.AuthenticateAsFinanceCheckerAsync();
        var reprocessResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/eta-notifications/{inboxMessageId}/reprocess",
            new ReprocessEtaDocumentNotificationRequest("ETA_SUPPORT", 0, "Manual support replay"));
        Assert.Equal(HttpStatusCode.OK, reprocessResponse.StatusCode);

        var receipt = await reprocessResponse.Content.ReadFromJsonAsync<EtaNotificationProcessingReceiptResponse>();
        Assert.NotNull(receipt);
        Assert.Equal("PROCESSED", receipt!.StatusCode);
        Assert.True(receipt.Reconciled);
        Assert.Equal(transmission.EtaTransmissionAttemptId, receipt.ReconciledTransmissionId);
        Assert.Equal("ACCEPTED", receipt.ReconciliationOutcome);

        var transmissionDetail = GetTransmission(transmission.EtaTransmissionAttemptId);
        Assert.NotNull(transmissionDetail);
        Assert.Equal("ACCEPTED", transmissionDetail!.StatusCode);
    }

    [Fact]
    public async Task Eta_Dispatch_Batch_Uses_Transport_Endpoint_When_Multiple_Live_Endpoints_Are_Active()
    {
        await ResetEtaEndpointStateAsync();
        var invoiceId = CreatePostedEtaInvoice();

        await _client.AuthenticateAsInternalAsync();
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA outbound transport endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/api/v1.0/transport/documentsubmissions",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-signing-secret");
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA auth endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/connect/token",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-client|eta-secret");
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA submit endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/api/v1.0/documentsubmissions",
            authenticationModeCode: "BEARER",
            credentialReference: null);
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA submission status endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "GET",
            relativePath: "/api/v1.0/submissions",
            authenticationModeCode: "BEARER",
            credentialReference: null);

        await _client.AuthenticateAsFinanceMakerAsync();
        var submitResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submit",
            new SubmitInvoiceToEtaRequest(ActorUserId: 0, PayloadText: null));
        var submission = await submitResponse.Content.ReadFromJsonAsync<EtaSubmissionLogResponse>();
        Assert.NotNull(submission);

        await _client.PostAsync($"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission!.EtaSubmissionLogId}/queue-transmission", null);

        var dispatchResult = DispatchEtaBatch();
        var transmission = Assert.Single(dispatchResult.Transmissions);
        Assert.Equal("DISPATCHED", transmission.StatusCode);
        Assert.NotNull(transmission.SignatureText);
        Assert.NotNull(transmission.AdapterReference);
    }

    [Fact]
    public async Task Eta_Authority_Status_Returns_NotLinked_When_Submission_Has_No_Authority_Uuid()
    {
        await ResetEtaEndpointStateAsync();
        long invoiceId;

        using (var scope = _factory.Services.CreateScope())
        {
            var invoiceService = scope.ServiceProvider.GetRequiredService<IAccountsReceivableInvoiceService>();

            var invoice = invoiceService.CreateInvoice(new CreateAccountsReceivableInvoiceRequest(
                CustomerId: 2,
                SalesOrderId: 1,
                DispatchOrderId: 1,
                InvoiceType: "TAX",
                InvoiceDate: new DateOnly(2026, 5, 29),
                TaxDate: new DateOnly(2026, 5, 29),
                DueDate: new DateOnly(2026, 6, 8),
                CurrencyCode: "EGP",
                Lines:
                [
                    new CreateAccountsReceivableInvoiceLineRequest(1, 1001, 2m, "EA", 32m, "VAT14")
                ]));

            invoiceId = AccountsReceivableWorkflowTestHelper
                .SubmitApproveAndPostInvoice(invoiceService, invoice.AccountsReceivableInvoiceId)
                .AccountsReceivableInvoiceId;
        }

        await _client.AuthenticateAsFinanceMakerAsync();

        var submitResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submit",
            new SubmitInvoiceToEtaRequest(ActorUserId: 0, PayloadText: null));
        Assert.Equal(HttpStatusCode.OK, submitResponse.StatusCode);

        var submission = await submitResponse.Content.ReadFromJsonAsync<EtaSubmissionLogResponse>();
        Assert.NotNull(submission);

        var response = await _client.GetAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission!.EtaSubmissionLogId}/authority-status");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var payload = await response.Content.ReadFromJsonAsync<EtaAuthoritySubmissionStatusResponse>();
        Assert.NotNull(payload);
        Assert.Equal(invoiceId, payload!.AccountsReceivableInvoiceId);
        Assert.Equal(submission.EtaSubmissionLogId, payload.EtaSubmissionLogId);
        Assert.Equal("NOT_LINKED", payload.LinkStatus);
        Assert.Equal("NOT_LINKED", payload.StatusCode);
        Assert.Null(payload.AuthoritySubmissionUuid);
        Assert.Empty(payload.Documents);
    }

    [Fact]
    public async Task Eta_Authority_Status_Uses_Stored_EtaUuid_When_Response_Text_Has_No_Authority_Uuid()
    {
        await ResetEtaEndpointStateAsync();
        var invoiceId = CreatePostedEtaInvoice();

        await _client.AuthenticateAsFinanceMakerAsync();

        var submitResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submit",
            new SubmitInvoiceToEtaRequest(ActorUserId: 0, PayloadText: null));
        Assert.Equal(HttpStatusCode.OK, submitResponse.StatusCode);

        var submission = await submitResponse.Content.ReadFromJsonAsync<EtaSubmissionLogResponse>();
        Assert.NotNull(submission);

        var responseRecord = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission!.EtaSubmissionLogId}/response",
            new RecordEtaInvoiceResponseRequest(
                ActorUserId: 0,
                StatusCode: "SUBMITTED",
                EtaUuid: "SUB-ETA-STORED-001",
                ResponseText: "{\"status\":\"SUBMITTED\"}",
                ErrorCode: null,
                ErrorMessage: null,
                NotesText: "Stored ETA UUID should be used for authority lookup fallback."));
        Assert.Equal(HttpStatusCode.OK, responseRecord.StatusCode);

        var response = await _client.GetAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission.EtaSubmissionLogId}/authority-status");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var payload = await response.Content.ReadFromJsonAsync<EtaAuthoritySubmissionStatusResponse>();
        Assert.NotNull(payload);
        Assert.Equal(invoiceId, payload!.AccountsReceivableInvoiceId);
        Assert.Equal(submission.EtaSubmissionLogId, payload.EtaSubmissionLogId);
        Assert.Equal("ENDPOINT_NOT_CONFIGURED", payload.LinkStatus);
        Assert.Equal("ENDPOINT_NOT_CONFIGURED", payload.StatusCode);
        Assert.Equal("SUB-ETA-STORED-001", payload.AuthoritySubmissionUuid);
    }

    [Fact]
    public async Task Eta_Authority_Status_Returns_Connectivity_Failure_Instead_Of_Throwing_When_Live_Auth_Cannot_Complete()
    {
        await ResetEtaEndpointStateAsync();
        var invoiceId = CreatePostedEtaInvoice();

        await _client.AuthenticateAsInternalAsync();
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA auth endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/connect/token",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-client|eta-secret");
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA submission status endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "GET",
            relativePath: "/api/v1.0/submissions",
            authenticationModeCode: "BEARER",
            credentialReference: null);

        await _client.AuthenticateAsFinanceMakerAsync();
        var submitResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submit",
            new SubmitInvoiceToEtaRequest(ActorUserId: 0, PayloadText: null));
        Assert.Equal(HttpStatusCode.OK, submitResponse.StatusCode);

        var submission = await submitResponse.Content.ReadFromJsonAsync<EtaSubmissionLogResponse>();
        Assert.NotNull(submission);

        var responseRecord = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission!.EtaSubmissionLogId}/response",
            new RecordEtaInvoiceResponseRequest(
                ActorUserId: 0,
                StatusCode: "SUBMITTED",
                EtaUuid: "SUB-ETA-CONNECTIVITY-001",
                ResponseText: "{\"status\":\"SUBMITTED\"}",
                ErrorCode: null,
                ErrorMessage: null,
                NotesText: "Connectivity-failure fallback test."));
        Assert.Equal(HttpStatusCode.OK, responseRecord.StatusCode);

        var response = await _client.GetAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission.EtaSubmissionLogId}/authority-status");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var payload = await response.Content.ReadFromJsonAsync<EtaAuthoritySubmissionStatusResponse>();
        Assert.NotNull(payload);
        Assert.Equal("LINKED", payload!.LinkStatus);
        Assert.Equal("AUTHORITY_CONNECTIVITY_FAILED", payload.StatusCode);
        Assert.Equal("SUB-ETA-CONNECTIVITY-001", payload.AuthoritySubmissionUuid);
    }

    [Fact]
    public async Task Eta_Callback_Reconciliation_Preserves_SubmissionUuid_For_Authority_Status_Fallback()
    {
        await ResetEtaEndpointStateAsync();
        var invoiceId = CreatePostedEtaInvoice();

        await _client.AuthenticateAsInternalAsync();
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA outbound transport endpoint",
            directionCode: "OUTBOUND",
            transportCode: "REST",
            httpMethodCode: "POST",
            relativePath: "/api/v1.0/transport/documentsubmissions",
            authenticationModeCode: "BASIC",
            credentialReference: "inline://eta-signing-secret");
        await CreateAndActivateEtaEndpointAsync(
            endpointName: "ETA document notifications endpoint",
            directionCode: "INBOUND",
            transportCode: "WEBHOOK",
            httpMethodCode: "PUT",
            relativePath: "/api/v1.0/notifications/documents",
            authenticationModeCode: "API_KEY",
            credentialReference: "inline://eta-callback-secret");

        await _client.AuthenticateAsFinanceMakerAsync();
        var submitResponse = await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submit",
            new SubmitInvoiceToEtaRequest(ActorUserId: 0, PayloadText: null));
        var submission = await submitResponse.Content.ReadFromJsonAsync<EtaSubmissionLogResponse>();
        Assert.NotNull(submission);
        await _client.PostAsJsonAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission!.EtaSubmissionLogId}/response",
            new RecordEtaInvoiceResponseRequest(
                ActorUserId: 0,
                StatusCode: "SUBMITTED",
                EtaUuid: null,
                ResponseText: "{\"authoritySubmissionUuid\":\"SUB-ETA-CALLBACK-001\"}",
                ErrorCode: null,
                ErrorMessage: null,
                NotesText: "Linked for callback submission UUID fallback test."));
        await _client.PostAsync($"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission.EtaSubmissionLogId}/queue-transmission", null);

        _client.DefaultRequestHeaders.Authorization = null;
        using (var callbackRequest = new HttpRequestMessage(HttpMethod.Put, "/api/v1/integrations/eta/notifications/documents"))
        {
            callbackRequest.Headers.TryAddWithoutValidation("Authorization", "ApiKey eta-callback-secret");
            callbackRequest.Content = new StringContent(
                """
                {
                  "notificationId": "ETA-NOTIF-SUBMISSION-UUID-001",
                  "type": "DocumentReceived",
                  "notifications": [
                    {
                      "submissionUUID": "SUB-ETA-CALLBACK-001",
                      "documentUUID": "DOC-ETA-CALLBACK-001",
                      "status": "Valid"
                    }
                  ]
                }
                """,
                System.Text.Encoding.UTF8,
                "application/json");

            using var callbackResponse = await _client.SendAsync(callbackRequest);
            Assert.Equal(HttpStatusCode.OK, callbackResponse.StatusCode);
        }

        await _client.AuthenticateAsFinanceMakerAsync();
        var response = await _client.GetAsync(
            $"/api/v1/finance/ar-invoices/{invoiceId}/eta-submissions/{submission.EtaSubmissionLogId}/authority-status");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var payload = await response.Content.ReadFromJsonAsync<EtaAuthoritySubmissionStatusResponse>();
        Assert.NotNull(payload);
        Assert.Equal("ENDPOINT_NOT_CONFIGURED", payload!.LinkStatus);
        Assert.Equal("SUB-ETA-CALLBACK-001", payload.AuthoritySubmissionUuid);
    }

    private async Task<IntegrationEndpointResponse> CreateAndActivateEtaEndpointAsync(
        string endpointName,
        string directionCode,
        string transportCode,
        string httpMethodCode,
        string relativePath,
        string authenticationModeCode,
        string? credentialReference,
        string environmentCode = "UAT")
    {
        var createResponse = await _client.PostAsJsonAsync("/api/v1/integrations/endpoints", new CreateIntegrationEndpointRequest(
            EndpointName: endpointName,
            IntegrationProviderCode: "ETA",
            EnvironmentCode: environmentCode,
            DirectionCode: directionCode,
            TransportCode: transportCode,
            HttpMethodCode: httpMethodCode,
            BaseUrl: "https://sdk.invoicing.eta.gov.eg",
            RelativePath: relativePath,
            AuthenticationModeCode: authenticationModeCode,
            CredentialReference: credentialReference,
            TimeoutSeconds: 20,
            RetryPolicyCode: "STANDARD",
            MaxRetryCount: 2,
            IsIdempotencyKeyRequired: true,
            Notes: "ETA Phase 1 QA endpoint"));
        Assert.Equal(HttpStatusCode.OK, createResponse.StatusCode);

        var created = await createResponse.Content.ReadFromJsonAsync<IntegrationEndpointResponse>();
        Assert.NotNull(created);

        Assert.Equal(HttpStatusCode.OK, (await _client.PostAsync($"/api/v1/integrations/endpoints/{created!.IntegrationEndpointId}/submit", null)).StatusCode);
        await _client.AuthenticateAsFinanceCheckerAsync();
        Assert.Equal(HttpStatusCode.OK, (await _client.PostAsync($"/api/v1/integrations/endpoints/{created.IntegrationEndpointId}/approve", null)).StatusCode);
        Assert.Equal(HttpStatusCode.OK, (await _client.PostAsync($"/api/v1/integrations/endpoints/{created.IntegrationEndpointId}/activate", null)).StatusCode);
        await _client.AuthenticateAsInternalAsync();
        return created;
    }

    private async Task ResetEtaEndpointStateAsync()
    {
        using var scope = _factory.Services.CreateScope();
        var dbContext = scope.ServiceProvider.GetRequiredService<CashLineErpDbContext>();

        var etaEndpoints = dbContext.IntegrationEndpointRegistryEntries
            .Where(entry => entry.IntegrationProviderCode == "ETA")
            .ToArray();
        var etaEndpointIds = etaEndpoints.Select(entry => entry.Id).ToArray();
        if (etaEndpoints.Length > 0)
        {
            dbContext.IntegrationEndpointRegistryEntries.RemoveRange(etaEndpoints);
        }

        var integrationWorkflows = dbContext.WorkflowInstances
            .Where(entry => entry.DocumentType == "INTEGRATION_ENDPOINT")
            .ToArray();
        if (integrationWorkflows.Length > 0)
        {
            dbContext.WorkflowInstances.RemoveRange(integrationWorkflows);
        }

        var integrationOutboxEvents = dbContext.OutboxEvents
            .Where(entry => entry.SourceModuleCode == "INTEGRATION")
            .ToArray();
        if (integrationOutboxEvents.Length > 0)
        {
            dbContext.OutboxEvents.RemoveRange(integrationOutboxEvents);
        }

        var etaInboxMessages = dbContext.InboxMessages
            .Where(entry => etaEndpointIds.Contains(entry.IntegrationEndpointId))
            .ToArray();
        if (etaInboxMessages.Length > 0)
        {
            dbContext.InboxMessages.RemoveRange(etaInboxMessages);
        }

        var etaOutboxEvents = dbContext.OutboxEvents
            .Where(entry => entry.SourceModuleCode == "ETA")
            .ToArray();
        if (etaOutboxEvents.Length > 0)
        {
            dbContext.OutboxEvents.RemoveRange(etaOutboxEvents);
        }

        var etaDocumentEvents = dbContext.EtaDocumentEvents.ToArray();
        if (etaDocumentEvents.Length > 0)
        {
            dbContext.EtaDocumentEvents.RemoveRange(etaDocumentEvents);
        }

        var etaTransmissions = dbContext.EtaTransmissionAttempts.ToArray();
        if (etaTransmissions.Length > 0)
        {
            dbContext.EtaTransmissionAttempts.RemoveRange(etaTransmissions);
        }

        var etaSubmissionLogs = dbContext.EtaSubmissionLogs.ToArray();
        if (etaSubmissionLogs.Length > 0)
        {
            dbContext.EtaSubmissionLogs.RemoveRange(etaSubmissionLogs);
        }

        await dbContext.SaveChangesAsync();
    }

    private long CreatePostedEtaInvoice()
    {
        using var scope = _factory.Services.CreateScope();
        var invoiceService = scope.ServiceProvider.GetRequiredService<IAccountsReceivableInvoiceService>();

        var invoice = invoiceService.CreateInvoice(new CreateAccountsReceivableInvoiceRequest(
            CustomerId: 2,
            SalesOrderId: 1,
            DispatchOrderId: 1,
            InvoiceType: "TAX",
            InvoiceDate: new DateOnly(2026, 5, 29),
            TaxDate: new DateOnly(2026, 5, 29),
            DueDate: new DateOnly(2026, 6, 8),
            CurrencyCode: "EGP",
            Lines:
            [
                new CreateAccountsReceivableInvoiceLineRequest(1, 1001, 2m, "EA", 32m, "VAT14")
            ]));

        return AccountsReceivableWorkflowTestHelper
            .SubmitApproveAndPostInvoice(invoiceService, invoice.AccountsReceivableInvoiceId)
            .AccountsReceivableInvoiceId;
    }

    private DispatchEtaTransmissionBatchResultResponse DispatchEtaBatch()
    {
        using var scope = _factory.Services.CreateScope();
        var etaComplianceService = scope.ServiceProvider.GetRequiredService<IEtaComplianceService>();
        return etaComplianceService.DispatchQueuedTransmissions(new DispatchEtaTransmissionBatchRequest("ETA_QA_DISPATCH", 5));
    }

    private EtaTransmissionAttemptResponse? GetTransmission(long etaTransmissionAttemptId)
    {
        using var scope = _factory.Services.CreateScope();
        var etaComplianceService = scope.ServiceProvider.GetRequiredService<IEtaComplianceService>();
        return etaComplianceService.GetTransmission(etaTransmissionAttemptId);
    }
}
