from unittest.mock import MagicMock, patch

import pytest

from plytix.auth import fetch_plytix_api_token
from plytix.client_factory import build_plytix_client


def test_fetch_plytix_api_token_extracts_access_token():
    response = MagicMock()
    response.json.return_value = {"data": [{"access_token": "tok-abc"}]}
    response.raise_for_status = MagicMock()

    with patch("plytix.auth.requests.post", return_value=response) as post:
        token = fetch_plytix_api_token("key", "secret")

    assert token == "tok-abc"
    post.assert_called_once()
    payload = post.call_args.kwargs["json"]
    assert payload == {"api_key": "key", "api_password": "secret"}


def test_fetch_plytix_api_token_requires_credentials():
    with pytest.raises(ValueError, match="PLYTIX_API_KEY"):
        fetch_plytix_api_token("", "")


def test_build_plytix_client_fetches_token_when_password_set():
    cfg = MagicMock(api_token="", api_key="key", api_password="secret", base_url="https://pim.plytix.com/api/v1")

    with patch("plytix.client_factory.fetch_plytix_api_token", return_value="fresh-token") as fetch:
        with patch("plytix.client_factory.PlytixApiClient") as client_cls:
            build_plytix_client(cfg)

    fetch.assert_called_once_with("key", "secret")
    client_cls.assert_called_once()
    assert client_cls.call_args.kwargs["api_token"] == "fresh-token"
