import logging

import pytest

from pipelet_ocpp_broker import _filter_auth_headers, _select_backend_auth


def test_select_backend_auth_prefers_incoming_when_config_empty():
    incoming = "Bearer inbound-token"

    used_key, source, headers = _select_backend_auth(
        incoming_key=incoming,
        db_key="",
        db_basic_user="",
        db_basic_password="",
        station_id="station-1",
    )

    assert used_key == incoming
    assert source == "incoming"
    assert headers == [("authorization", incoming)]


def test_select_backend_auth_ignores_incomplete_basic_override(caplog: pytest.LogCaptureFixture):
    caplog.set_level(logging.WARNING)

    used_key, source, headers = _select_backend_auth(
        incoming_key=None,
        db_key=None,
        db_basic_user="",
        db_basic_password="secret",
        station_id="station-2",
    )

    assert used_key is None
    assert source is None
    assert headers is None
    assert any(
        "Backend Basic Auth override incomplete" in record.getMessage()
        for record in caplog.records
    )


def test_filter_auth_headers_omits_empty_values(caplog: pytest.LogCaptureFixture):
    caplog.set_level(logging.WARNING)

    headers = _filter_auth_headers(
        [
            ("authorization", "   "),
            ("X-Test", "value"),
        ],
        station_id="station-3",
    )

    assert headers == [("X-Test", "value")]
    assert any(
        "Omitting 1 empty Authorization header" in record.getMessage()
        for record in caplog.records
    )
