"""Tests for andlake.nessie."""

from __future__ import annotations

import sys
from unittest.mock import MagicMock

import pytest

from andlake.config import reset_config


REQUIRED_ENV = {
    "ANDLAKE_TENANT_ID": "tenant-abc",
    "ANDLAKE_ACCESS_TOKEN": "jwt-token",
}


@pytest.fixture(autouse=True)
def _clean_config():
    reset_config()
    yield
    reset_config()


@pytest.fixture()
def mock_pynessie(monkeypatch: pytest.MonkeyPatch):
    """Install a mock ``pynessie`` package into sys.modules."""
    mock = MagicMock()
    monkeypatch.setitem(sys.modules, "pynessie", mock)
    return mock


class TestGetNessieClient:
    """get_nessie_client() returns a properly configured NessieClient."""

    def test_default_endpoint(
        self, monkeypatch: pytest.MonkeyPatch, mock_pynessie: MagicMock
    ):
        for key, val in REQUIRED_ENV.items():
            monkeypatch.setenv(key, val)

        mock_client = MagicMock()
        mock_pynessie.NessieClient.return_value = mock_client

        from andlake.nessie import get_nessie_client

        client = get_nessie_client()

        mock_pynessie.NessieClient.assert_called_once_with(
            config={"endpoint": "http://nessie:19120/api/v2"},
        )
        assert client is mock_client

    def test_custom_endpoint(
        self, monkeypatch: pytest.MonkeyPatch, mock_pynessie: MagicMock
    ):
        for key, val in REQUIRED_ENV.items():
            monkeypatch.setenv(key, val)
        monkeypatch.setenv("NESSIE_URI", "http://custom-nessie:19120/api/v2")

        mock_pynessie.NessieClient.return_value = MagicMock()

        from andlake.nessie import get_nessie_client

        get_nessie_client()

        mock_pynessie.NessieClient.assert_called_once_with(
            config={"endpoint": "http://custom-nessie:19120/api/v2"},
        )
