import pytest
from unittest.mock import patch, MagicMock
from token_service_tool.token_service import TokenService


# -------------------------
# Test 1: Missing parameters
# -------------------------
def test_missing_parameters():
    with pytest.raises(ValueError) as exc:
        TokenService(
            client_id="",
            client_secret="secret",
            tenant_id="tenant",
            scope="scope",
            token_url="https://example.com",
            grant_type="client_credentials"
        )

    assert "Missing required parameters" in str(exc.value)


# -------------------------
# Test 2: Successful token fetch
# -------------------------
@patch("my_package.token_service.requests.post")
def test_get_access_token_success(mock_post):
    # Mock the response object
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {"access_token": "dummy_token"}
    mock_post.return_value = mock_response

    service = TokenService(
        client_id="id",
        client_secret="secret",
        tenant_id="tenant",
        scope="scope",
        token_url="https://example.com",
        grant_type="client_credentials"
    )

    token = service.get_access_token()
    assert token == "dummy_token"
    mock_post.assert_called_once()


# -------------------------
# Test 3: HTTP failure
# -------------------------
@patch("my_package.token_service.requests.post")
def test_get_access_token_http_failure(mock_post):
    mock_response = MagicMock()
    mock_response.status_code = 400
    mock_response.text = "Bad Request"
    mock_post.return_value = mock_response

    service = TokenService(
        client_id="id",
        client_secret="secret",
        tenant_id="tenant",
        scope="scope",
        token_url="https://example.com",
        grant_type="client_credentials"
    )

    with pytest.raises(Exception) as exc:
        service.get_access_token()

    assert "Failed to get token" in str(exc.value)


# -------------------------
# Test 4: Missing access_token in response
# -------------------------
@patch("my_package.token_service.requests.post")
def test_get_access_token_missing_token(mock_post):
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {}  # no access_token
    mock_post.return_value = mock_response

    service = TokenService(
        client_id="id",
        client_secret="secret",
        tenant_id="tenant",
        scope="scope",
        token_url="https://example.com",
        grant_type="client_credentials"
    )

    with pytest.raises(Exception) as exc:
        service.get_access_token()

    assert "Token not found in response" in str(exc.value)
