from app.config import settings


def _create_partner(client):
    settings.admin_api_key = "test-admin"
    settings.allow_unsafe_admin = False
    resp = client.post(
        "/v1/partners",
        json={"name": "Demo Partner"},
        headers={"X-Admin-Key": settings.admin_api_key},
    )
    assert resp.status_code == 201
    data = resp.json()
    return data["api_key"], data["id"]


def test_checkout_requires_api_key(client_with_db):
    resp = client_with_db.post(
        "/v1/checkout-sessions",
        json={
            "partner_id": "any",
            "external_order_id": "ORDER-1",
            "amount": 10.0,
            "currency": "USD",
        },
    )
    assert resp.status_code == 401


def test_dashboard_requires_api_key(client_with_db):
    resp = client_with_db.get("/dashboard")
    assert resp.status_code == 401


def test_admin_key_required_for_partner_creation(client_with_db):
    settings.admin_api_key = "test-admin"
    settings.allow_unsafe_admin = False
    resp = client_with_db.post("/v1/partners", json={"name": "No Key"})
    assert resp.status_code == 401


def test_checkout_and_payout_update(client_with_db):
    api_key, partner_id = _create_partner(client_with_db)
    session = client_with_db.post(
        "/v1/checkout-sessions",
        headers={"X-API-Key": api_key},
        json={
            "partner_id": partner_id,
            "external_order_id": "ORDER-1",
            "amount": 25.0,
            "currency": "USD",
            "consent_analytics": True,
        },
    )
    assert session.status_code == 201
    session_id = session.json()["id"]
    assert session.json()["consent_analytics"] is True

    payout = client_with_db.post(
        f"/v1/checkout-sessions/{session_id}/payout",
        json={"payout_status": "paid"},
        headers={"X-Admin-Key": settings.admin_api_key},
    )
    assert payout.status_code == 200
    assert payout.json()["payout_status"] == "paid"


def test_payout_update_requires_admin_key(client_with_db):
    api_key, partner_id = _create_partner(client_with_db)
    session = client_with_db.post(
        "/v1/checkout-sessions",
        headers={"X-API-Key": api_key},
        json={
            "partner_id": partner_id,
            "external_order_id": "ORDER-5",
            "amount": 15.0,
            "currency": "USD",
        },
    )
    session_id = session.json()["id"]
    resp = client_with_db.post(
        f"/v1/checkout-sessions/{session_id}/payout",
        json={"payout_status": "paid"},
    )
    assert resp.status_code == 401
