import pytest

from integrations.mcp.security import authenticate_mcp_caller


@pytest.mark.asyncio
async def test_authenticate_mcp_caller_with_resolved_agent_key(monkeypatch):
    async def _fake_resolve(provided_api_key: str):
        del provided_api_key
        from security.auth.api_keys import ResolvedAPIKey

        return ResolvedAPIKey(
            key_id="kid-1",
            agent_id="agent-1",
            scopes=["*"],
            is_active=True,
            expires_at=None,
        )

    monkeypatch.setattr("integrations.mcp.security.resolve_agent_api_key", _fake_resolve)
    principal = await authenticate_mcp_caller("ak-test")
    assert principal.agent_id == "agent-1"
    assert principal.key_id == "kid-1"


@pytest.mark.asyncio
async def test_authenticate_mcp_caller_rejects_missing_key(monkeypatch):
    async def _fake_resolve(provided_api_key: str):
        del provided_api_key
        return None

    monkeypatch.setattr("integrations.mcp.security.resolve_agent_api_key", _fake_resolve)
    with pytest.raises(PermissionError):
        await authenticate_mcp_caller(None)


@pytest.mark.asyncio
async def test_authenticate_mcp_caller_rejects_invalid_key(monkeypatch):
    async def _fake_resolve(provided_api_key: str):
        del provided_api_key
        return None

    monkeypatch.setattr("integrations.mcp.security.resolve_agent_api_key", _fake_resolve)
    with pytest.raises(PermissionError):
        await authenticate_mcp_caller("invalid")



