import pytest

from py_ullr.rest.records import RecordsAPI
from py_ullr.exceptions import ArcherAPIException, ResourceNotFoundError, ValidationError
from py_ullr.client import ArcherConfig


class DummyAuth:
    def __init__(self):
        self.is_authenticated = True

    def get_headers(self):
        return {}

    def get_session(self):
        return self._session

    def set_session(self, session):
        self._session = session


class MockResponse:
    def __init__(self, status_code=200, json_data=None, headers=None):
        self.status_code = status_code
        self._json = json_data or {}
        self.headers = headers or {}

    def json(self):
        return self._json

    def raise_for_status(self):
        if self.status_code >= 400:
            raise Exception("http error")


class MockSession:
    def __init__(self, response):
        self._response = response
        self.request_calls = []

    def request(self, method, url, headers=None, timeout=None, **kwargs):
        self.request_calls.append((method, url, headers, kwargs))
        return self._response


def test_create_returns_id_and_payload_contains_fieldcontents():
    dummy_auth = DummyAuth()
    response = MockResponse(status_code=201, json_data={"RequestedObject": {"Id": 123}})
    mock_session = MockSession(response)
    dummy_auth.set_session(mock_session)

    config = ArcherConfig(base_url="https://example", instance_name="inst")
    api = RecordsAPI(dummy_auth, config)

    record_id = api.create(10, {"Title": "x", "Count": 5})
    assert record_id == 123

    # Inspect the last request made by the mock session
    method, url, headers, kwargs = mock_session.request_calls[-1]
    assert "json" in kwargs
    assert kwargs["json"]["Content"]["LevelId"] == 10
    assert "FieldContents" in kwargs["json"]["Content"]


def test_get_raises_resource_not_found():
    dummy_auth = DummyAuth()
    config = ArcherConfig(base_url="https://example", instance_name="inst")
    api = RecordsAPI(dummy_auth, config)

    def raise_404(method, url, **kwargs):
        raise ArcherAPIException("404 Not Found")

    api._make_request = raise_404

    with pytest.raises(ResourceNotFoundError):
        api.get(999)


def test_create_validation_error_is_translated_to_validationerror():
    dummy_auth = DummyAuth()
    config = ArcherConfig(base_url="https://example", instance_name="inst")
    api = RecordsAPI(dummy_auth, config)

    def raise_validation(method, url, **kwargs):
        raise ArcherAPIException("validation error: bad")

    api._make_request = raise_validation

    with pytest.raises(ValidationError):
        api.create(1, {"f": "v"})
