"""Testes da verificação de webhook (HMAC)."""

from __future__ import annotations

import hashlib
import hmac
import json

import pytest

from abacapython import webhooks
from abacapython.exceptions import WebhookSignatureError

SECRET = "s3cr3t"
PAYLOAD = json.dumps({"event": "checkout.completed", "data": {"id": "chk_1"}}).encode("utf-8")


def _sign(payload: bytes, secret: str = SECRET) -> str:
    return hmac.new(secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()


def test_verify_signature_ok():
    assert webhooks.verify_signature(PAYLOAD, _sign(PAYLOAD), SECRET) is True


def test_verify_signature_accepts_string_payload():
    raw = PAYLOAD.decode()
    assert webhooks.verify_signature(raw, _sign(raw.encode()), SECRET) is True


def test_verify_signature_with_prefix():
    sig = f"sha256={_sign(PAYLOAD)}"
    assert webhooks.verify_signature(PAYLOAD, sig, SECRET) is True


def test_verify_signature_bad():
    with pytest.raises(WebhookSignatureError):
        webhooks.verify_signature(PAYLOAD, "deadbeef", SECRET)


def test_verify_signature_empty():
    with pytest.raises(WebhookSignatureError):
        webhooks.verify_signature(PAYLOAD, "", SECRET)


def test_parse_event_returns_model():
    event = webhooks.parse_event(PAYLOAD, _sign(PAYLOAD), SECRET)
    assert event.event == "checkout.completed"
    assert event.data == {"id": "chk_1"}


def test_parse_event_unwraps_envelope():
    payload = json.dumps(
        {
            "data": {"event": "transparent.completed", "data": {"id": "pix_1"}},
            "success": True,
        }
    ).encode("utf-8")
    event = webhooks.parse_event(payload, _sign(payload), SECRET)
    assert event.event == "transparent.completed"
    assert event.data == {"id": "pix_1"}


def test_parse_event_rejects_empty():
    with pytest.raises(ValueError):
        webhooks.parse_event(b"", _sign(b""), SECRET)


def test_extract_signature_case_insensitive():
    headers = {"X-AbacatePay-Signature": "abc123"}
    assert webhooks.extract_signature(headers) == "abc123"


def test_extract_signature_alternate_header():
    headers = {"x-signature": "xyz"}
    assert webhooks.extract_signature(headers) == "xyz"
