import pytest
from httpx import AsyncClient

USER_PAYLOAD = {
    "email": "stats_user@inphb.ci",
    "motDePasse": "TestPass123!",
    "nom": "Konate",
    "prenom": "Aicha",
}

SIGNALEMENT_PAYLOAD = {
    "titre": "Signalement stats",
    "description": "Signalement pour tester le dashboard utilisateur",
    "type": "HARCELEMENT_MORAL",
    "modeIdentification": "ANONYME",
}


async def _get_token(client: AsyncClient) -> str:
    await client.post("/api/v1/auth/signup", json=USER_PAYLOAD)
    login = await client.post(
        "/api/v1/auth/login",
        json={"email": USER_PAYLOAD["email"], "motDePasse": USER_PAYLOAD["motDePasse"]},
    )
    return login.json()["data"]["token"]


@pytest.mark.asyncio
async def test_dashboard_stats_for_regular_user(client: AsyncClient):
    token = await _get_token(client)
    await client.post(
        "/api/v1/signalements/",
        json=SIGNALEMENT_PAYLOAD,
        headers={"Authorization": f"Bearer {token}"},
    )

    response = await client.get(
        "/api/v1/stats/dashboard",
        headers={"Authorization": f"Bearer {token}"},
    )

    assert response.status_code == 200
    data = response.json()["data"]
    assert data["totalSignalements"] >= 1
    assert data["signalementsNouveaux"] >= 1


@pytest.mark.asyncio
async def test_dashboard_alerts_and_recent_ids_are_strings(client: AsyncClient):
    token = await _get_token(client)
    create = await client.post(
        "/api/v1/signalements/",
        json=SIGNALEMENT_PAYLOAD,
        headers={"Authorization": f"Bearer {token}"},
    )
    created_id = create.json()["data"]["id"]

    alerts_response = await client.get(
        "/api/v1/stats/dashboard/alerts?limit=5",
        headers={"Authorization": f"Bearer {token}"},
    )
    assert alerts_response.status_code == 200

    alertes = alerts_response.json()["data"]["alertes"]
    assert any(item["id"] == created_id for item in alertes)
    assert all(isinstance(item["id"], str) for item in alertes)

    recent_response = await client.get(
        "/api/v1/stats/dashboard/cases/recent?limit=5",
        headers={"Authorization": f"Bearer {token}"},
    )
    assert recent_response.status_code == 200

    dossiers = recent_response.json()["data"]["dossiers"]
    assert any(item["id"] == created_id for item in dossiers)
    assert all(isinstance(item["id"], str) for item in dossiers)
