"""Création de commande : le serveur est seul juge des prix, des fichiers et du consentement."""
from conftest import DEMO_CODE, NOCONSENT_CODE


def _payload(code=DEMO_CODE, **over):
    base = {
        "family_code": code,
        "customer_name": "Famille Test",
        "customer_email": "test@example.com",
        "items": [{
            "photo_filename": "portrait.jpg", "format_id": "print-10x15", "format_label": "Tirage 10x15",
            "quantity": 2, "unit_price": 9.0, "is_magic": False,
        }],
        "total": 18.0,
    }
    base.update(over)
    return base


async def test_create_order_without_stripe_key(client, demo_code):
    r = await client.post("/api/portal/orders", json=_payload())
    assert r.status_code == 200, r.text
    body = r.json()
    assert body["success"] is True
    assert body["client_secret"] is None
    orders = (await client.get(f"/api/portal/orders?code={demo_code}")).json()["orders"]
    mine = next(o for o in orders if o["id"] == body["order_id"])
    assert mine["payment_status"] == "unpaid"
    assert mine["downloads"] == []


async def test_order_rejects_inconsistent_total(client):
    r = await client.post("/api/portal/orders", json=_payload(total=999.0))
    assert r.status_code == 400


async def test_order_rejects_tampered_unit_price(client):
    """Un client ne peut pas se fixer son propre prix."""
    p = _payload(total=0.02)
    p["items"][0]["unit_price"] = 0.01
    r = await client.post("/api/portal/orders", json=p)
    assert r.status_code == 400


async def test_order_rejects_unknown_format_and_missing_photo(client):
    p = _payload()
    p["items"][0]["format_id"] = "poster-gratuit"
    assert (await client.post("/api/portal/orders", json=p)).status_code == 400
    p = _payload()
    p["items"][0]["photo_filename"] = "../../etc/passwd"
    assert (await client.post("/api/portal/orders", json=p)).status_code == 400
    p = _payload()
    p["items"][0]["photo_filename"] = "inexistante.jpg"
    assert (await client.post("/api/portal/orders", json=p)).status_code == 400


async def test_order_requires_consent(client):
    from core.db import get_db
    with get_db() as conn:
        conn.execute("UPDATE families SET consent_at=NULL WHERE code=?", (NOCONSENT_CODE,))
        conn.commit()
    p = _payload(code=NOCONSENT_CODE)
    p["items"][0]["photo_filename"] = "solo.jpg"
    assert (await client.post("/api/portal/orders", json=p)).status_code == 403


async def test_order_rejects_unknown_family(client):
    assert (await client.post("/api/portal/orders", json=_payload(code="ZZZ-0000"))).status_code == 404


async def test_magic_format_requires_a_generated_photo(client):
    """Un format « magique » sur une photo normale (génération simulée) est refusé."""
    p = _payload(total=14.0)
    p["items"] = [{"photo_filename": "portrait.jpg", "format_id": "magic-print", "format_label": "Magique",
                   "quantity": 1, "unit_price": 14.0, "is_magic": True}]
    assert (await client.post("/api/portal/orders", json=p)).status_code == 400


async def test_order_uses_school_specific_prices(client, admin_headers):
    r = await client.put("/api/admin/settings", json={"settings": {"price_print_10x15": 11}}, headers=admin_headers)
    assert r.status_code == 200
    try:
        # ancien prix → refusé
        assert (await client.post("/api/portal/orders", json=_payload())).status_code == 400
        p = _payload(total=22.0)
        p["items"][0]["unit_price"] = 11.0
        assert (await client.post("/api/portal/orders", json=p)).status_code == 200
        assert (await client.get(f"/api/portal/photos?code={DEMO_CODE}")).json()["pricing"]["print_10x15"] == 11
    finally:
        await client.put("/api/admin/settings", json={"settings": {"price_print_10x15": 9}}, headers=admin_headers)
