"""Tests standard target features using the built-in SDK tests library."""

from __future__ import annotations

import typing as t

import pytest
from singer_sdk.testing import get_target_test_class

from target_kafka.target import TargetKafka

# Minimal config for standard SDK tests (KafkaProducer is mocked in conftest.py)
SAMPLE_CONFIG: dict[str, t.Any] = {
    "bootstrap_servers": "localhost:9092",
}


# Run standard built-in target tests from the SDK:
StandardTargetTests = get_target_test_class(
    target_class=TargetKafka,
    config=SAMPLE_CONFIG,
)


class TestTargetKafka(StandardTargetTests):  # type: ignore[misc, valid-type]
    """Standard Target Tests."""

    @pytest.fixture(scope="class")
    def resource(self):  # noqa: ANN201
        """Generic external resource.

        This fixture is useful for setup and teardown of external resources,
        such output folders, tables, buckets etc. for use during testing.

        Example usage can be found in the SDK samples test suite:
        https://github.com/meltano/sdk/tree/main/tests/packages
        """
        return "resource"

    def test_common_topic_uses_single_topic_and_adds_stream_field(
        self,
    ) -> None:
        """When common_topic is set, sink uses that topic and adds 'stream' to each record."""
        from target_kafka.sinks import KafkaSink
        from target_kafka.target import TargetKafka

        config = {
            **SAMPLE_CONFIG,
            "common_topic": "raw-events",
        }
        target = TargetKafka(config=config)
        schema = {"type": "object", "properties": {"id": {"type": "integer"}}}
        sink = KafkaSink(target, "my_stream", schema, ["id"])

        assert sink.topic_name == "raw-events"
        assert sink.get_validator() is None

        sink.start_batch({})
        sink.process_record({"id": 1, "name": "a"}, {})
        assert len(sink._batch) == 1
        assert sink._batch[0]["stream"] == "my_stream"
        assert sink._batch[0]["id"] == 1

    def test_common_topic_unset_uses_stream_name_and_prefix(
        self,
    ) -> None:
        """When common_topic is unset, topic is prefix + stream_name (or stream_name)."""
        from target_kafka.sinks import KafkaSink
        from target_kafka.target import TargetKafka

        config = {**SAMPLE_CONFIG, "topic_prefix": "env-"}
        target = TargetKafka(config=config)
        schema = {"type": "object", "properties": {"x": {"type": "integer"}}}
        sink = KafkaSink(target, "stream_a", schema, [])

        assert sink.topic_name == "env-stream_a"
        assert sink.get_validator() is not None

        sink.start_batch({})
        sink.process_record({"x": 1}, {})
        assert "stream" not in sink._batch[0]


