from unittest.mock import patch

import pytest

from upstox_auth import MemoryStorage, UpstoxAuthenticator


@pytest.fixture
def auth():
    return UpstoxAuthenticator(
        api_key="test_key",
        api_secret="test_secret",
        redirect_uri="http://localhost/callback",
        mobile_no="1234567890",
        pin="123456",
        totp_key="TESTTOTP",
        storage=MemoryStorage(),
    )


def test_auth_url_generation(auth):
    url = auth.generate_auth_url()
    assert "client_id=test_key" in url
    assert "redirect_uri=http%3A%2F%2Flocalhost%2Fcallback" in url
    assert "response_type=code" in url


@patch("requests.post")
def test_exchange_code(mock_post, auth):
    # Mock successful Upstox API response
    mock_post.return_value.status_code = 200
    mock_post.return_value.json.return_value = {"access_token": "mock_token_123"}

    result = auth.exchange_code_for_token("test_code")

    assert result["access_token"] == "mock_token_123"
    assert auth.storage.get_token()["access_token"] == "mock_token_123"
