import pytest

from metaverse.config import settings
from metaverse.tools.dashboards import (
    add_card_to_dashboard,
    create_dashboard,
    get_dashboard,
    list_dashboards,
)
from tests.conftest import json_response


@pytest.fixture
def dashboard():
    return {
        "id": 5,
        "name": "Sales Overview",
        "description": "Monthly sales metrics",
        "dashcards": [
            {
                "id": 1,
                "card_id": 42,
                "card": {"name": "Revenue by Month"},
                "row": 0,
                "col": 0,
                "size_x": 12,
                "size_y": 8,
                "series": [],
                "parameter_mappings": [],
                "visualization_settings": {},
            }
        ],
    }


async def test_list_dashboards(mock_api, dashboard):
    mock_api.get("/dashboard").mock(return_value=json_response([dashboard]))
    result = await list_dashboards()
    assert len(result) == 1
    assert result[0]["name"] == "Sales Overview"
    assert "description" in result[0]


async def test_get_dashboard(mock_api, dashboard):
    mock_api.get("/dashboard/5").mock(return_value=json_response(dashboard))
    result = await get_dashboard(5)
    assert result["id"] == 5
    assert len(result["cards"]) == 1
    assert result["cards"][0]["name"] == "Revenue by Month"
    assert result["url"] == f"{settings.url}/dashboard/5"


async def test_create_dashboard(mock_api):
    mock_api.post("/dashboard").mock(
        return_value=json_response({"id": 9, "name": "New Dashboard", "description": ""})
    )
    result = await create_dashboard("New Dashboard")
    assert result["id"] == 9
    assert result["url"] == f"{settings.url}/dashboard/9"


async def test_add_card_to_dashboard(mock_api, dashboard):
    mock_api.get("/dashboard/5").mock(return_value=json_response(dashboard))
    mock_api.put("/dashboard/5/cards").mock(
        return_value=json_response({"cards": dashboard["dashcards"] + [{"id": 2}]})
    )
    result = await add_card_to_dashboard(5, 99, row=0, col=12)
    assert result["dashboard_id"] == 5
    assert result["card_count"] == 2
