import pytest

from metaverse.tools.alerts import create_alert, delete_alert, list_alerts
from tests.conftest import json_response

_NOTIFICATION = {
    "id": 7,
    "payload_type": "notification/card",
    "payload": {
        "card_id": 42,
        "card": {"name": "Refunds per Provider"},
        "send_condition": "has_result",
    },
    "active": True,
}


@pytest.fixture
def notification():
    return _NOTIFICATION


async def test_list_alerts(mock_api, notification):
    mock_api.get("/notification").mock(return_value=json_response([notification]))
    result = await list_alerts()
    assert len(result) == 1
    assert result[0]["id"] == 7
    assert result[0]["card_id"] == 42
    assert result[0]["send_condition"] == "has_result"
    assert result[0]["active"] is True


async def test_list_alerts_filters_non_card(mock_api):
    other = {"id": 1, "payload_type": "notification/slack", "payload": {}}
    mock_api.get("/notification").mock(return_value=json_response([other]))
    result = await list_alerts()
    assert result == []


async def test_list_alerts_empty(mock_api):
    mock_api.get("/notification").mock(return_value=json_response([]))
    result = await list_alerts()
    assert result == []


async def test_create_alert_rows_alias(mock_api, notification):
    mock_api.get("/user/current").mock(return_value=json_response({"id": 1}))
    mock_api.post("/notification").mock(return_value=json_response(notification))
    result = await create_alert(42, alert_condition="rows")
    assert result["id"] == 7
    assert result["card_id"] == 42
    assert result["send_condition"] == "has_result"
    assert result["active"] is True


async def test_create_alert_has_result(mock_api, notification):
    mock_api.get("/user/current").mock(return_value=json_response({"id": 1}))
    mock_api.post("/notification").mock(return_value=json_response(notification))
    result = await create_alert(42, alert_condition="has_result")
    assert result["send_condition"] == "has_result"


async def test_delete_alert(mock_api, notification):
    mock_api.get("/notification/7").mock(return_value=json_response(notification))
    mock_api.put("/notification/7").mock(
        return_value=json_response({**notification, "active": False})
    )
    result = await delete_alert(7)
    assert result == {"deleted": True, "alert_id": 7}
