# edited by glg
import pytest

from pypos.modules.sinkronisasi.services.event_ingestion_backpressure_service import (
    EventIngestionBackpressureService,
)
from pypos.modules.sinkronisasi.services.event_ingestion_gateway_service import (
    EventIngestionGatewayService,
)
from pypos.modules.sinkronisasi.services.event_outbox_service import EventOutboxService


pytestmark = [pytest.mark.unit]


def test_ingestion_gateway_enqueue_with_dedup(tmp_path):
    db_path = tmp_path / "gateway_outbox.db"
    outbox_service = EventOutboxService(str(db_path))
    backpressure_service = EventIngestionBackpressureService({"default_batch": 2})
    gateway = EventIngestionGatewayService(
        outbox_service=outbox_service,
        backpressure_service=backpressure_service,
    )

    events = [
        {"transaksi_id": "TRX-001", "nominal": 15000},
        {"transaksi_id": "TRX-001", "nominal": 15000},
        {"transaksi_id": "TRX-002", "nominal": 9000},
    ]
    result = gateway.ingest_events(
        topic="transaksi.created",
        events=events,
        source_id="CBG-01",
    )

    assert result["accepted"] is True
    assert result["ingested_count"] == 2
    assert result["duplicate_count"] == 1
    assert result["dropped_count"] == 0
    assert result["total_events"] == 3

    metrics = outbox_service.get_queue_metrics()
    assert metrics["pending"] == 2
    assert metrics["inflight"] == 0


def test_ingestion_gateway_block_when_backpressure_critical(tmp_path):
    db_path = tmp_path / "gateway_outbox_critical.db"
    outbox_service = EventOutboxService(str(db_path))
    backpressure_service = EventIngestionBackpressureService({"pending_critical": 1})
    gateway = EventIngestionGatewayService(
        outbox_service=outbox_service,
        backpressure_service=backpressure_service,
    )

    result = gateway.ingest_events(
        topic="transaksi.created",
        events=[{"transaksi_id": "TRX-001"}],
        source_id="CBG-01",
        metrics={"pending": 1, "inflight": 0, "error_rate_pct": 0.0, "avg_latency_ms": 0.0},
    )

    assert result["accepted"] is False
    assert result["mode"] == "critical"
    assert result["ingested_count"] == 0
    assert result["dropped_count"] == 1
