from __future__ import annotations

from typing import Any

import pytest

from amsdal_ml.utils.reference_utils import build_reference_payload
from amsdal_ml.utils.reference_utils import resolve_reference_resource


def test_resolve_reference_resource_returns_connection_name(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(
        'amsdal_ml.utils.reference_utils.AmsdalConfigManager.get_connection_name_by_model_name',
        lambda _self, model_name: f'conn_for_{model_name.lower()}',
    )

    assert resolve_reference_resource('Category') == 'conn_for_category'


def test_resolve_reference_resource_returns_none_on_error(monkeypatch: pytest.MonkeyPatch) -> None:
    def _raise_error(_self: Any, _model_name: str) -> str:
        msg = 'lookup failed'
        raise RuntimeError(msg)

    monkeypatch.setattr(
        'amsdal_ml.utils.reference_utils.AmsdalConfigManager.get_connection_name_by_model_name',
        _raise_error,
    )

    assert resolve_reference_resource('Category') is None


def test_build_reference_payload_includes_resolved_resource(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(
        'amsdal_ml.utils.reference_utils.resolve_reference_resource',
        lambda model_name: f'conn_for_{model_name.lower()}',
    )

    payload = build_reference_payload('Category', 123)

    assert payload == {
        '$ref': {
            'class_name': 'Category',
            'object_id': '123',
            'resource': 'conn_for_category',
        }
    }


def test_build_reference_payload_omits_resource_when_unknown(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr('amsdal_ml.utils.reference_utils.resolve_reference_resource', lambda _model_name: None)

    payload = build_reference_payload('Category', '123')

    assert payload == {
        '$ref': {
            'class_name': 'Category',
            'object_id': '123',
        }
    }
