"""Tests for DLQ synchronous wrappers."""

from __future__ import annotations

import pytest

from pycharter.etl_generator._dlq_sync import (
    add_batch_sync,
    add_record_sync,
    retry_record_sync,
)
from pycharter.etl_generator.dlq import DeadLetterQueue, DLQReason

# Suppress utcnow deprecation from upstream DLQ code we don't own
pytestmark = pytest.mark.filterwarnings("ignore::DeprecationWarning")


def _make_dlq(enabled: bool = True) -> DeadLetterQueue:
    """Create a memory-backed DLQ for testing."""
    return DeadLetterQueue(enabled=enabled, storage_backend="memory")


class TestDLQSyncWrappers:
    """Tests for add_record_sync, add_batch_sync, retry_record_sync."""

    def test_add_record_sync_memory_backend(self):
        """Adding a record via sync wrapper stores it in memory."""
        dlq = _make_dlq()
        record = add_record_sync(
            dlq=dlq,
            pipeline_name="test_pipeline",
            record_data={"id": 1, "value": "bad"},
            reason=DLQReason.VALIDATION_ERROR,
            error_message="field 'x' is required",
            error_type="ValueError",
            stage="extract",
        )
        assert record is not None
        assert record.pipeline_name == "test_pipeline"
        assert record.reason == DLQReason.VALIDATION_ERROR
        assert record.stage == "extract"

    def test_add_record_sync_disabled_returns_none(self):
        """Disabled DLQ returns None without error."""
        dlq = _make_dlq(enabled=False)
        record = add_record_sync(
            dlq=dlq,
            pipeline_name="test_pipeline",
            record_data={"id": 1},
            reason=DLQReason.VALIDATION_ERROR,
            error_message="err",
            error_type="ValueError",
            stage="load",
        )
        assert record is None

    def test_add_batch_sync_multiple_records(self):
        """Batch sync wrapper stores multiple records."""
        dlq = _make_dlq()
        records = add_batch_sync(
            dlq=dlq,
            pipeline_name="batch_pipeline",
            batch=[{"id": 1}, {"id": 2}, {"id": 3}],
            reason=DLQReason.LOAD_ERROR,
            error_message="connection timeout",
            error_type="ConnectionError",
            stage="load",
        )
        assert len(records) == 3
        assert all(r.pipeline_name == "batch_pipeline" for r in records)

    def test_retry_record_sync_marks_for_retry(self):
        """retry_record_sync marks a record for retry."""
        dlq = _make_dlq()
        record = add_record_sync(
            dlq=dlq,
            pipeline_name="retry_pipeline",
            record_data={"id": 99},
            reason=DLQReason.TRANSFORMATION_ERROR,
            error_message="transform failed",
            error_type="RuntimeError",
            stage="transform",
        )
        assert record is not None
        result = retry_record_sync(dlq=dlq, record_id=record.id)
        assert result is True
