"""Native tests for PowerPath client wiring."""

from __future__ import annotations

import os
from unittest.mock import patch

import pytest

from timeback_powerpath import PowerPathClient


class TestPowerPathClientInit:
    def test_staging_environment(self) -> None:
        client = PowerPathClient(env="staging", client_id="id", client_secret="secret")
        assert "staging" in client._transport.base_url

    def test_production_environment(self) -> None:
        client = PowerPathClient(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) -> None:
        with patch.dict(
            os.environ,
            {
                "POWERPATH_CLIENT_ID": "id",
                "POWERPATH_CLIENT_SECRET": "secret",
                "POWERPATH_TOKEN_URL": "https://auth.example.com/oauth2/token",
            },
        ):
            client = PowerPathClient(
                base_url="https://custom.example.com",
                auth_url="https://auth.example.com/oauth2/token",
            )
            assert client._transport.base_url == "https://custom.example.com"

    def test_explicit_credentials(self) -> None:
        client = PowerPathClient(env="staging", client_id="my-id", client_secret="my-secret")
        assert client._provider is not None

    def test_missing_credentials_raises(self) -> None:
        with (
            patch.dict(os.environ, {}, clear=True),
            pytest.raises(ValueError, match="Missing required environment variable"),
        ):
            PowerPathClient(env="staging")


class TestPowerPathClientTransport:
    def test_get_transport(self) -> None:
        client = PowerPathClient(env="staging", client_id="id", client_secret="secret")
        transport = client.get_transport()
        assert transport.base_url is not None


class TestPowerPathClientCheckAuth:
    @pytest.mark.asyncio
    async def test_check_auth_raises_without_provider(self) -> None:
        from timeback_common import PowerPathPaths

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

            async def close(self) -> None:
                return None

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


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