"""Basic tests for pylibrus async functionality."""

from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from pylibrus import auth, exceptions
from pylibrus.resources import Librus


@pytest.mark.asyncio
async def test_user_credentials_success():
    """Test successful user authentication."""
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "access_token": "test_access_token",
        "refresh_token": "test_refresh_token",
    }

    with patch("pylibrus.auth.base_post_rq", new_callable=AsyncMock) as mock_post:
        mock_post.return_value = mock_response

        access_token, refresh_token = await auth.user_credentials("user", "pass")

        assert access_token == "test_access_token"
        assert refresh_token == "test_refresh_token"


@pytest.mark.asyncio
async def test_user_credentials_failure():
    """Test failed user authentication."""
    mock_response = MagicMock()
    mock_response.status_code = 401

    with patch("pylibrus.auth.base_post_rq", new_callable=AsyncMock) as mock_post:
        mock_post.return_value = mock_response

        with pytest.raises(exceptions.InvalidCredentials):
            await auth.user_credentials("user", "wrong_pass")


@pytest.mark.asyncio
async def test_refresh_token_success():
    """Test successful token refresh."""
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "access_token": "new_access_token",
        "refresh_token": "new_refresh_token",
    }

    with patch("pylibrus.auth.base_post_rq", new_callable=AsyncMock) as mock_post:
        mock_post.return_value = mock_response

        access_token, refresh_token = await auth.refresh_token("old_refresh_token")

        assert access_token == "new_access_token"
        assert refresh_token == "new_refresh_token"


@pytest.mark.asyncio
async def test_librus_get_resource():
    """Test getting a resource from Librus API."""
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {"data": "test_data"}

    with patch("pylibrus.resources.base_get_rq", new_callable=AsyncMock) as mock_get:
        mock_get.return_value = mock_response

        async with Librus("test_access_token") as client:
            result = await client.getResource("Me")

            assert result == {"data": "test_data"}


@pytest.mark.asyncio
async def test_librus_get_resource_error():
    """Test API error when getting resource."""
    mock_response = MagicMock()
    mock_response.status_code = 404
    mock_response.json.return_value = {"error": "not_found"}

    with patch("pylibrus.resources.base_get_rq", new_callable=AsyncMock) as mock_get:
        mock_get.return_value = mock_response

        async with Librus("test_access_token") as client:
            with pytest.raises(exceptions.APIError):
                await client.getResource("InvalidResource")
