"""POST /api/v1/records/{record_id}/memorial — router-level coverage.

Every other memorial test calls MemorialService.create_for_record directly,
which never builds a MemorialResponse. That gap let a half-applied change ship:
a relationship was added to the response schema without being added to the
create path's eager-load, so serialising the new memorial attempted lazy-load
IO and the endpoint 500'd with MissingGreenlet.

These tests go through the router so that class of bug cannot recur silently.
"""
import pytest
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession


async def _make_record(db: AsyncSession, tenant_id, *, first="Jane", last="Doe"):
    from src.apps.records.models.record import Record

    rec = Record(tenant_id=tenant_id, first_name=first, last_name=last, status="active")
    db.add(rec)
    await db.flush()
    return rec


@pytest.mark.asyncio
async def test_create_memorial_returns_201_with_all_relationships_serialised(
    client: AsyncClient, db_session: AsyncSession, test_account, auth_headers
):
    """The reported bug: this returned 500 because `photos` was in
    MemorialResponse but missing from the create path's eager-load."""
    record = await _make_record(db_session, test_account.id)

    resp = await client.post(
        f"/api/v1/records/{record.id}/memorial",
        json={"display_name": "Jane Doe", "is_published": False},
        headers={**auth_headers, "X-Tenant-ID": str(test_account.id)},
    )

    assert resp.status_code == 201, resp.text
    data = resp.json()["data"]
    assert data["slug"] == "jane-doe"
    # Every relationship on MemorialResponse must serialise without lazy IO.
    assert data["photos"] == []
    assert data["tributes"] == []
    assert data["timeline_events"] == []


@pytest.mark.asyncio
async def test_create_path_eager_loads_every_relationship_on_the_response():
    """Guard for the next time a relationship is added to MemorialResponse.

    Fails loudly here rather than as a runtime 500 if the schema gains a
    relationship the create query does not eager-load.
    """
    import inspect

    from src.apps.memorials.models.memorial import Memorial
    from src.apps.memorials.schemas.responses import MemorialResponse
    from src.apps.memorials.services import memorial_service

    # Relationship-typed fields on the response = what must be pre-loaded.
    relationship_names = {
        name for name in MemorialResponse.model_fields
        if hasattr(Memorial, name)
        and hasattr(getattr(Memorial, name).property, "mapper")
    }

    source = inspect.getsource(memorial_service.MemorialService.create_for_record)
    eager_loaded = {
        name for name in relationship_names
        if f"selectinload(Memorial.{name})" in source
    }

    missing = relationship_names - eager_loaded
    assert not missing, (
        f"MemorialResponse exposes {sorted(missing)} but create_for_record does "
        f"not eager-load them — serialising the new memorial will raise "
        f"MissingGreenlet. Add selectinload(Memorial.<name>) to the reload."
    )
