from easybill_client.webhooks import EasybillWebhookParser


def test_parser_reads_headers_and_payload():
    parser = EasybillWebhookParser(secret="topsecret")

    payload = {"id": 42, "number": "RE-42"}
    headers = {
        "X-easybill-Event": "document.completed",
        "X-easybill-Webhook-Delivery": "4711",
    }

    envelope = parser.parse_json(headers=headers, payload=payload)

    assert envelope.event == "document.completed"
    assert envelope.delivery_id == "4711"
    assert envelope.resource_id == 42
    assert envelope.payload == payload


def test_parser_supports_form_encoded_payload():
    parser = EasybillWebhookParser()

    headers = {
        "X-easybill-Event": "customer.update",
        "X-easybill-Webhook-Delivery": "99",
    }
    form_data = {
        "id": "15",
        "customer_id": "15",
        "company_name": "ACME GmbH",
    }

    envelope = parser.parse_form(headers=headers, form_data=form_data)

    assert envelope.event == "customer.update"
    assert envelope.delivery_id == "99"
    assert envelope.resource_id == 15
    assert envelope.payload["company_name"] == "ACME GmbH"


def test_generic_parse_and_acknowledgement():
    parser = EasybillWebhookParser()

    headers = {
        "X-easybill-Event": "document.completed",
        "X-easybill-Webhook-Delivery": "123",
    }

    envelope = parser.parse(
        headers=headers,
        payload={"id": 7, "status": "done"},
        content_type="application/json",
    )

    assert envelope.event == "document.completed"
    assert envelope.resource_id == 7
    assert parser.build_acknowledgement() == {"status": "ok"}
