"""Test Ontology service implementation."""

import json
import os
from unittest import mock

from databuilder_logic_sdk.core.ontology import OntologyService, create_ontology_service

from .utils import gen_test_config, reset_global_config


def test_add_bce_headers_when_access_key_is_present() -> None:
    """Test ontology request headers include BCE keys when access key is configured."""
    reset_global_config()
    mock_config = gen_test_config(
        ontology={
            "endpoint": "http://ontology.service",
            "token": "ontology_service_token",
            "bceAccessKey": "access-key",
            "bceSecurityKey": "security-key",
            "bceSecurityToken": "security-token",
        }
    )

    with mock.patch.dict(os.environ, {"ServiceConfig": json.dumps(mock_config)}):
        service = create_ontology_service()

    assert isinstance(service, OntologyService)

    mock_response = mock.Mock()
    mock_response.raise_for_status.return_value = None
    mock_response.json.return_value = {"code": "SUCCESS", "message": "", "result": {"data": []}}

    with mock.patch("databuilder_logic_sdk.core.ontology.requests.post", return_value=mock_response) as mock_post:
        response = service.search(
            {
                "ontology": "test",
                "apiName": "test_api",
            }
        )

    assert response.code == "SUCCESS"
    headers = mock_post.call_args.kwargs["headers"]
    assert headers["Authorization"] == "ontology_service_token"
    assert headers["x-bce-access-key"] == "access-key"
    assert headers["x-bce-security-key"] == "security-key"
    assert headers["x-bce-security-token"] == "security-token"


def test_do_not_add_bce_headers_when_access_key_is_empty() -> None:
    """Test ontology request headers do not include BCE keys when access key is empty."""
    reset_global_config()
    mock_config = gen_test_config(
        ontology={
            "endpoint": "http://ontology.service",
            "token": "ontology_service_token",
            "bceAccessKey": "   ",
            "bceSecurityKey": "security-key",
            "bceSecurityToken": "security-token",
        }
    )

    with mock.patch.dict(os.environ, {"ServiceConfig": json.dumps(mock_config)}):
        service = create_ontology_service()

    assert isinstance(service, OntologyService)

    mock_response = mock.Mock()
    mock_response.raise_for_status.return_value = None
    mock_response.json.return_value = {"code": "SUCCESS", "message": "", "result": {"data": []}}

    with mock.patch("databuilder_logic_sdk.core.ontology.requests.post", return_value=mock_response) as mock_post:
        response = service.search(
            {
                "ontology": "test",
                "apiName": "test_api",
            }
        )

    assert response.code == "SUCCESS"
    headers = mock_post.call_args.kwargs["headers"]
    assert headers["Authorization"] == "ontology_service_token"
    assert "x-bce-access-key" not in headers
    assert "x-bce-security-key" not in headers
    assert "x-bce-security-token" not in headers


def test_add_bce_headers_with_legacy_config_keys() -> None:
    """Test legacy x-bce-* config keys still work for request headers."""
    reset_global_config()
    mock_config = gen_test_config(
        ontology={
            "endpoint": "http://ontology.service",
            "token": "ontology_service_token",
            "x-bce-access-key": "legacy-access-key",
            "x-bce-security-key": "legacy-security-key",
            "x-bce-security-token": "legacy-security-token",
        }
    )

    with mock.patch.dict(os.environ, {"ServiceConfig": json.dumps(mock_config)}):
        service = create_ontology_service()

    mock_response = mock.Mock()
    mock_response.raise_for_status.return_value = None
    mock_response.json.return_value = {"code": "SUCCESS", "message": "", "result": {"data": []}}

    with mock.patch("databuilder_logic_sdk.core.ontology.requests.post", return_value=mock_response) as mock_post:
        service.search(
            {
                "ontology": "test",
                "apiName": "test_api",
            }
        )

    headers = mock_post.call_args.kwargs["headers"]
    assert headers["x-bce-access-key"] == "legacy-access-key"
    assert headers["x-bce-security-key"] == "legacy-security-key"
    assert headers["x-bce-security-token"] == "legacy-security-token"
