"""Testes da construção do cliente e configuração."""

from __future__ import annotations

import pytest

from abacapython import AbacaPay, AsyncAbacaPay
from abacapython._http import DEFAULT_BASE_URL


def test_api_key_required(monkeypatch):
    monkeypatch.delenv("ABACATEPAY_API_KEY", raising=False)
    with pytest.raises(ValueError, match="API key"):
        AbacaPay()


def test_api_key_from_env(monkeypatch):
    monkeypatch.setenv("ABACATEPAY_API_KEY", "abc_env_xyz")
    client = AbacaPay()
    assert client.base_url == DEFAULT_BASE_URL
    client.close()


def test_api_key_from_arg_takes_precedence(monkeypatch):
    monkeypatch.setenv("ABACATEPAY_API_KEY", "abc_env_xyz")
    client = AbacaPay(api_key="abc_arg_abc")
    assert client.base_url == DEFAULT_BASE_URL
    client.close()


def test_base_url_can_be_overridden():
    client = AbacaPay(api_key="abc_x", base_url="https://staging.example.com/v2/")
    # base_url é normalizado (sem trailing slash).
    assert client.base_url == "https://staging.example.com/v2"
    client.close()


def test_sync_context_manager():
    with AbacaPay(api_key="abc_x") as client:
        assert client.base_url == DEFAULT_BASE_URL


@pytest.mark.asyncio
async def test_async_context_manager():
    async with AsyncAbacaPay(api_key="abc_x") as client:
        assert client.base_url == DEFAULT_BASE_URL


def test_resources_attached():
    client = AbacaPay(api_key="abc_x")
    for attr in (
        "customers",
        "products",
        "checkouts",
        "payment_links",
        "pix_qrcodes",
        "coupons",
        "webhooks",
        "subscriptions",
        "payouts",
        "pix_transfers",
        "store",
        "trust_mrr",
    ):
        assert hasattr(client, attr), f"client.{attr} faltando"
    client.close()
