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


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


# -------------------------
# Test 2: Successful token fetch
# -------------------------
@patch("token_service_tool.token_service.requests.post")
def test_get_access_token_success(mock_post):
    mock_resp = MagicMock()
    mock_resp.status_code = 200
    mock_resp.json.return_value = {"access_token": "dummy_token"}
    mock_post.return_value = mock_resp

    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"


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

    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):
        service.get_access_token()


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

    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):
        service.get_access_token()
