"""
Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com

Tests for server SSL configuration builder.
"""

from pathlib import Path
from typing import Dict

from _pytest.monkeypatch import MonkeyPatch

import pytest

from mcp_proxy_adapter.core.app_factory import ssl_config as ssl_module


class _DummySSLManager:
    """Minimal SSLManager stub for unit tests."""

    def __init__(self, config: object) -> None:
        self.config = config


@pytest.fixture(autouse=True)
def _stub_ssl_manager(monkeypatch: MonkeyPatch) -> None:
    """Patch SSLManager to avoid loading real certificates."""

    monkeypatch.setattr(ssl_module, "SSLManager", _DummySSLManager)


def _create_cert_files(tmp_path: Path) -> Dict[str, str]:
    """Create placeholder certificate files."""

    cert = tmp_path / "server.crt"
    key = tmp_path / "server.key"
    ca = tmp_path / "ca.crt"
    for file in (cert, key, ca):
        file.write_text("dummy-cert")
    return {"cert": str(cert), "key": str(key), "ca": str(ca)}


def test_build_server_ssl_config_https(tmp_path: Path) -> None:
    paths = _create_cert_files(tmp_path)
    app_cfg = {
        "server": {
            "protocol": "https",
            "ssl": {
                "cert": paths["cert"],
                "key": paths["key"],
                "ca": paths["ca"],
                "dnscheck": True,
            },
        }
    }

    result = ssl_module.build_server_ssl_config(app_cfg)

    assert result["certfile"] == paths["cert"]
    assert result["keyfile"] == paths["key"]
    assert result["ca_certs"] == paths["ca"]
    assert result["check_hostname"] is True
    assert result["verify_client"] is False


def test_build_server_ssl_config_http_returns_empty(tmp_path: Path) -> None:
    paths = _create_cert_files(tmp_path)
    app_cfg = {
        "server": {
            "protocol": "http",
            "ssl": {
                "cert": paths["cert"],
                "key": paths["key"],
                "ca": paths["ca"],
            },
        }
    }

    result = ssl_module.build_server_ssl_config(app_cfg)

    assert result == {}


def test_build_server_ssl_config_fallback_to_legacy_root(tmp_path: Path) -> None:
    paths = _create_cert_files(tmp_path)
    app_cfg = {
        "server": {
            "protocol": "https",
            "host": "0.0.0.0",
            "port": 8080,
        },
        "ssl": {
            "enabled": True,
            "cert_file": paths["cert"],
            "key_file": paths["key"],
            "ca_cert_file": paths["ca"],
            "dnscheck": False,
        },
    }

    result = ssl_module.build_server_ssl_config(app_cfg)

    assert result["certfile"] == paths["cert"]
    assert result["verify_client"] is False


def test_build_server_ssl_config_https_missing_ssl_raises() -> None:
    app_cfg = {"server": {"protocol": "https"}}

    with pytest.raises(ValueError):
        ssl_module.build_server_ssl_config(app_cfg)
