from dataclasses import replace
from unittest.mock import patch

from cog_mcp.auth import create_cognite_client
from cog_mcp.config import Config


def test_create_cognite_client_uses_default_azure_ad_flow(sample_config: Config) -> None:
    with (
        patch("cog_mcp.auth.OAuthClientCredentials") as oauth_cls,
        patch("cog_mcp.auth.CogniteClient") as cognite_client_cls,
    ):
        creds = object()
        oauth_cls.default_for_azure_ad.return_value = creds
        cognite_client = object()
        cognite_client_cls.return_value = cognite_client

        result = create_cognite_client(sample_config)

    assert result is cognite_client
    oauth_cls.default_for_azure_ad.assert_called_once_with(
        tenant_id=sample_config.tenant_id,
        client_id=sample_config.client_id,
        client_secret=sample_config.client_secret,
        cdf_cluster=sample_config.cluster,
    )
    oauth_cls.assert_not_called()

    client_config = cognite_client_cls.call_args.args[0]
    assert client_config.client_name == "cog-mcp-experimental"
    assert client_config.project == sample_config.project
    assert client_config.credentials is creds
    assert client_config.base_url == f"https://{sample_config.cluster}.cognitedata.com"


def test_create_cognite_client_uses_custom_token_url_when_present(sample_config: Config) -> None:
    config = replace(sample_config, token_url="https://login.example.com/custom-token")

    with (
        patch("cog_mcp.auth.OAuthClientCredentials") as oauth_cls,
        patch("cog_mcp.auth.CogniteClient") as cognite_client_cls,
    ):
        creds = object()
        oauth_cls.return_value = creds
        cognite_client_cls.return_value = object()

        create_cognite_client(config)

    oauth_cls.assert_called_once_with(
        token_url=config.token_url,
        client_id=config.client_id,
        client_secret=config.client_secret,
        scopes=[f"https://{config.cluster}.cognitedata.com/.default"],
    )
    oauth_cls.default_for_azure_ad.assert_not_called()
