"""Python-native tests for Webhooks client construction and behavior."""

import os
from unittest.mock import patch

import pytest

from timeback_webhooks import WebhooksClient


class TestWebhooksClientInit:
    """Tests for client initialization."""

    def test_staging_environment(self):
        client = WebhooksClient(env="staging", client_id="id", client_secret="secret")
        assert client._transport.base_url is not None

    def test_production_environment(self):
        client = WebhooksClient(env="production", client_id="id", client_secret="secret")
        assert "dev" not in client._transport.base_url
        assert "staging" not in client._transport.base_url

    def test_custom_base_url(self):
        client = WebhooksClient(
            base_url="https://custom.example.com",
            auth_url="https://auth.example.com/oauth2/token",
            client_id="id",
            client_secret="secret",
        )
        assert client._transport.base_url == "https://custom.example.com"

    def test_explicit_credentials(self):
        client = WebhooksClient(
            env="staging",
            client_id="my-id",
            client_secret="my-secret",
        )
        assert client._provider is not None
        tm = client._provider.get_token_manager("webhooks")
        assert tm is not None
        assert tm._config.client_id == "my-id"
        assert tm._config.client_secret == "my-secret"

    def test_missing_credentials_raises(self):
        with patch.dict(os.environ, {}, clear=True):
            os.environ.pop("WEBHOOKS_CLIENT_ID", None)
            os.environ.pop("WEBHOOKS_CLIENT_SECRET", None)
            os.environ.pop("TIMEBACK_API_CLIENT_ID", None)
            os.environ.pop("TIMEBACK_API_CLIENT_SECRET", None)
            os.environ.pop("TIMEBACK_CLIENT_ID", None)
            os.environ.pop("TIMEBACK_CLIENT_SECRET", None)
            with pytest.raises(ValueError, match="Missing required environment variable"):
                WebhooksClient(env="staging")

    def test_default_platform_is_beyond_ai(self):
        client = WebhooksClient(env="staging", client_id="id", client_secret="secret")
        assert client._transport.base_url is not None

    def test_beyond_ai_platform(self):
        client = WebhooksClient(
            platform="BEYOND_AI",
            env="staging",
            client_id="id",
            client_secret="secret",
        )
        assert client._transport.base_url is not None

    def test_custom_provider(self):
        client = WebhooksClient(
            base_url="https://custom.api.com",
            auth_url="https://custom.auth.com/token",
            client_id="test-id",
            client_secret="test-secret",
        )
        assert client._transport.base_url == "https://custom.api.com"


class TestWebhooksClientTransport:
    """Tests for transport access."""

    def test_get_transport(self):
        client = WebhooksClient(env="staging", client_id="id", client_secret="secret")

        transport = client.get_transport()
        assert transport is not None
        assert transport.base_url is not None

    def test_transport_has_webhook_paths(self):
        client = WebhooksClient(env="staging", client_id="id", client_secret="secret")

        transport = client.get_transport()
        assert hasattr(transport, "paths")
        assert transport.paths.webhook_list == "/webhooks/"
        assert transport.paths.webhook_filter_list == "/webhook-filters/"


class TestWebhooksClientCheckAuth:
    """Tests for check_auth."""

    @pytest.mark.asyncio
    async def test_check_auth_raises_without_provider(self):
        from timeback_common import WebhookPaths

        class MockTransport:
            base_url = "https://mock.api.com"
            paths = WebhookPaths()

            async def close(self) -> None:
                pass

        client = WebhooksClient(transport=MockTransport())

        with pytest.raises(RuntimeError, match="Cannot check auth"):
            await client.check_auth()


class TestWebhooksClientPlatformSupport:
    """Tests for platform-specific behavior."""

    def test_learnwith_ai_platform_raises(self):
        with pytest.raises(ValueError, match=r"not configured|not supported"):
            WebhooksClient(
                platform="LEARNWITH_AI",
                env="staging",
                client_id="id",
                client_secret="secret",
            )

    def test_learnwith_ai_path_profile_raises(self):
        from timeback_common import TimebackProvider

        provider = TimebackProvider(
            base_url="https://custom.api.com",
            auth_url="https://custom.auth.com/token",
            client_id="id",
            client_secret="secret",
            path_profile="LEARNWITH_AI",
        )
        with pytest.raises(ValueError, match=r"not supported"):
            WebhooksClient(provider=provider)

    def test_learnwith_ai_path_profile_with_custom_webhook_paths_succeeds(self):
        from timeback_common import TimebackProvider, WebhookPaths

        provider = TimebackProvider(
            base_url="https://custom.api.com",
            auth_url="https://custom.auth.com/token",
            client_id="id",
            client_secret="secret",
            path_profile="LEARNWITH_AI",
            paths={"webhooks": WebhookPaths()},
        )
        client = WebhooksClient(provider=provider)
        assert client._transport.base_url == "https://custom.api.com"


class TestWebhooksClientContextManager:
    """Tests for context manager support."""

    @pytest.mark.asyncio
    async def test_context_manager(self):
        async with WebhooksClient(env="staging", client_id="id", client_secret="secret") as client:
            assert client._provider is not None
