# app/tests/unit/market_data/acquisition/adapters/dzengi/test_candle_rest.py

from __future__ import annotations

import pytest

from src.market_data.acquisition.adapters.dzengi.rest import (
    DzengiCandlesDocumentSource,
)
from src.market_data.acquisition.exceptions import CandleTransportError


class StubPayloadRestClient:
    def __init__(
        self,
        *,
        result: object = None,
        error: Exception | None = None,
    ) -> None:
        self.result = result
        self.error = error
        self.calls: list[
            tuple[str, dict[str, str] | None, dict[str, str] | None]
        ] = []

    def get_payload(
        self,
        path: str,
        params: dict[str, str] | None = None,
        headers: dict[str, str] | None = None,
    ) -> object:
        self.calls.append((path, params, headers))

        if self.error is not None:
            raise self.error

        return self.result


def test_fetch_candles_document_calls_klines_endpoint() -> None:
    document = {"klines": []}
    client = StubPayloadRestClient(result=document)
    source = DzengiCandlesDocumentSource(client=client)

    result = source.fetch_candles_document(
        "BTC/USD",
        interval="5m",
        limit=200,
        price_type="ask",
    )

    assert result is document
    assert client.calls == [
        (
            "/api/v1/klines",
            {
                "symbol": "BTC/USD",
                "interval": "5m",
                "limit": "200",
                "priceType": "ask",
            },
            None,
        )
    ]


def test_fetch_candles_document_does_not_transform_document() -> None:
    document = [
        [1000, "100", "110", "90", "105", "12.5"],
    ]
    client = StubPayloadRestClient(result=document)
    source = DzengiCandlesDocumentSource(client=client)

    result = source.fetch_candles_document(
        "BTC/USD",
        interval="1m",
        limit=1,
        price_type="bid",
    )

    assert result is document


def test_fetch_candles_document_wraps_transport_error() -> None:
    original_error = RuntimeError("transport unavailable")
    client = StubPayloadRestClient(error=original_error)
    source = DzengiCandlesDocumentSource(client=client)

    with pytest.raises(
        CandleTransportError,
        match="Не удалось получить свечи",
    ) as error_info:
        source.fetch_candles_document(
            "BTC/USD",
            interval="1m",
            limit=100,
            price_type="bid",
        )

    assert error_info.value.__cause__ is original_error
