from unittest.mock import Mock

import pytest
from requests.exceptions import HTTPError

from finops_batches.exceptions import BatchExecutionError
from finops_batches.providers.gcp.rest_client import GcpRestClient


def test_post_pagination_and_close():
    session = Mock()
    first = Mock()
    first.json.return_value = {"nextPageToken": "next"}
    second = Mock()
    second.json.return_value = {"items": [1]}
    session.post.side_effect = [first, second]
    client = GcpRestClient(session)
    params = {"filter": "x"}
    assert list(client.pages("https://example.invalid", params, method="POST")) == [
        first.json.return_value,
        second.json.return_value,
    ]
    assert session.post.call_args_list[1].kwargs["params"] == {
        "filter": "x",
        "pageToken": "next",
    }
    assert params == {"filter": "x"}
    session.get.assert_not_called()
    client.close()
    session.close.assert_called_once_with()


def test_http_failure_is_not_empty_result():
    session = Mock()
    session.get.return_value.raise_for_status.side_effect = HTTPError("403")
    with pytest.raises(BatchExecutionError, match="GCP API request failed") as exc:
        list(GcpRestClient(session).pages("https://example.invalid"))
    assert isinstance(exc.value.__cause__, HTTPError)


def test_invalid_response_type():
    session = Mock()
    session.get.return_value.json.return_value = []
    with pytest.raises(TypeError, match="GCP_INVALID_RESPONSE"):
        list(GcpRestClient(session).pages("https://example.invalid"))


def test_invalid_pagination_token_type():
    session = Mock()
    session.get.return_value.json.return_value = {"nextPageToken": 42}
    with pytest.raises(ValueError, match="GCP_INVALID_PAGINATION_TOKEN"):
        list(GcpRestClient(session).pages("https://example.invalid"))
