from __future__ import annotations

import pytest

from konstant.config import ForwardConfig
from konstant.forwarder import ElasticsearchForwarder


class _FakeResponse:
    def __init__(self, payload: bytes) -> None:
        self._payload = payload

    def read(self) -> bytes:
        return self._payload

    def __enter__(self) -> "_FakeResponse":
        return self

    def __exit__(self, exc_type, exc, tb) -> bool:
        return False


def _forwarder() -> ElasticsearchForwarder:
    cfg = ForwardConfig(
        enabled=True,
        type="elasticsearch",
        url="http://localhost:9200",
        index="konstant-logs",
    )
    forwarder = object.__new__(ElasticsearchForwarder)
    forwarder._config = cfg
    return forwarder


def test_bulk_response_errors_true_raises(monkeypatch) -> None:
    monkeypatch.setattr(
        "konstant.forwarder.urllib.request.urlopen",
        lambda req, timeout=10: _FakeResponse(b'{"errors": true}'),
    )
    with pytest.raises(RuntimeError):
        _forwarder()._send_batch(['{"message":"x"}'])


def test_bulk_response_errors_false_is_ok(monkeypatch) -> None:
    monkeypatch.setattr(
        "konstant.forwarder.urllib.request.urlopen",
        lambda req, timeout=10: _FakeResponse(b'{"errors": false}'),
    )
    _forwarder()._send_batch(['{"message":"x"}'])
