from core.db import get_db
from conftest import NOCONSENT_CODE


async def test_consent_flow_is_idempotent(client):
    with get_db() as conn:  # état de départ garanti : pas de consentement
        conn.execute("UPDATE families SET consent_at=NULL, consent_ip=NULL WHERE code=?", (NOCONSENT_CODE,))
        conn.commit()

    r = await client.get(f"/api/portal/photos?code={NOCONSENT_CODE}")
    assert r.json()["consent_given"] is False

    r = await client.post("/api/portal/consent", json={"family_code": NOCONSENT_CODE})
    assert r.status_code == 200
    assert r.json()["consent_given"] is True
    first_consent_at = r.json()["consent_at"]

    r = await client.get(f"/api/portal/photos?code={NOCONSENT_CODE}")
    body = r.json()
    assert body["consent_given"] is True
    assert len(body["photos"]) == 1  # les photos n'apparaissent qu'après le consentement

    r2 = await client.post("/api/portal/consent", json={"family_code": NOCONSENT_CODE})
    assert r2.status_code == 200
    assert r2.json()["consent_at"] == first_consent_at


async def test_consent_unknown_code_404(client):
    r = await client.post("/api/portal/consent", json={"family_code": "ZZZ-9999"})
    assert r.status_code == 404
