import pytest

from telegram_gateway_verification.client import TelegramGatewayClient
from telegram_gateway_verification.exceptions import (
    TelegramGatewayAPIError,
    TelegramGatewayValidationError,
)


class DummyResponse:
    def __init__(self, payload: dict, status_code: int = 200) -> None:
        self._payload = payload
        self.status_code = status_code

    def json(self) -> dict:
        return self._payload


class DummySession:
    def __init__(self, payload: dict, status_code: int = 200) -> None:
        self.payload = payload
        self.status_code = status_code
        self.headers = {}
        self.last_url = None
        self.last_json = None

    def post(self, url: str, json: dict, timeout: float):
        self.last_url = url
        self.last_json = json
        return DummyResponse(self.payload, self.status_code)


def test_send_verification_message_success() -> None:
    payload = {
        "ok": True,
        "result": {
            "request_id": "req_1",
            "phone_number": "+15551234567",
            "request_cost": 0.01,
        },
    }
    session = DummySession(payload)
    client = TelegramGatewayClient(api_token="token", session=session)

    result = client.send_verification_message(phone_number="+15551234567", code_length=6)

    assert result.request_id == "req_1"
    assert session.last_url.endswith("/sendVerificationMessage")
    assert session.last_json == {"phone_number": "+15551234567", "code_length": 6}


def test_client_validation_rejects_bad_phone() -> None:
    client = TelegramGatewayClient(api_token="token", session=DummySession({"ok": True}))

    with pytest.raises(TelegramGatewayValidationError):
        client.check_send_ability(phone_number="12345")


def test_api_error_raises_exception() -> None:
    payload = {"ok": False, "error": "ACCESS_TOKEN_INVALID"}
    client = TelegramGatewayClient(api_token="token", session=DummySession(payload, 401))

    with pytest.raises(TelegramGatewayAPIError):
        client.check_send_ability(phone_number="+15551234567")
