from __future__ import annotations

import pytest

from kyrodb.auth import api_key_metadata, merge_metadata, redact_metadata, redact_sensitive_text


def test_api_key_metadata_none() -> None:
    assert api_key_metadata(None) == ()


def test_api_key_metadata_rejects_blank() -> None:
    with pytest.raises(ValueError, match="non-empty"):
        api_key_metadata("   ")


def test_api_key_metadata_rejects_control_chars() -> None:
    with pytest.raises(ValueError, match="invalid control"):
        api_key_metadata("abc\n123")


def test_merge_metadata_validates_pairs() -> None:
    with pytest.raises(ValueError, match="non-empty"):
        merge_metadata((("x-api-key", "k"),), [("", "v")])


def test_redact_sensitive_text_masks_auth_headers() -> None:
    raw = "request failed: x-api-key: abc123 Authorization=BearerToken"
    redacted = redact_sensitive_text(raw)
    assert "abc123" not in redacted
    assert "BearerToken" not in redacted
    assert "<redacted>" in redacted


def test_redact_sensitive_text_masks_full_authorization_value() -> None:
    raw = "grpc details: Authorization: Bearer very-secret-token"
    redacted = redact_sensitive_text(raw)
    assert "very-secret-token" not in redacted
    assert "Bearer very-secret-token" not in redacted
    assert "Authorization: <redacted>" in redacted


def test_redact_sensitive_text_masks_proxy_authorization_quoted_value() -> None:
    raw = 'upstream error proxy-authorization="Bearer token-123"'
    redacted = redact_sensitive_text(raw)
    assert "token-123" not in redacted
    assert 'proxy-authorization="<redacted>"' in redacted


def test_redact_metadata_masks_sensitive_keys() -> None:
    metadata = (("x-api-key", "abc123"), ("tenant", "acme"))
    redacted = redact_metadata(metadata)
    assert ("x-api-key", "<redacted>") in redacted
    assert ("tenant", "acme") in redacted
