"""Provider-neutral helpers for classic Mollie webhook notifications."""

from __future__ import annotations

from hashlib import sha256
from typing import Any, Mapping

from .provider import MollieResponseError, payment_status


def notification_reference(payload: Mapping[str, Any]) -> str:
    """Return the only value sent by Mollie's classic webhook contract."""
    reference = str(payload.get("id") or "").strip()
    if not reference.startswith(("tr_", "ord_")):
        raise MollieResponseError(
            "Mollie webhook did not contain a valid payment reference."
        )
    return reference


def event_fingerprint(payment: Mapping[str, Any] | Any) -> str:
    """Produce a stable idempotency key from the remotely fetched state."""
    identifier = str(payment.get("id") if hasattr(payment, "get") else "")
    if not identifier:
        raise MollieResponseError("Mollie response did not include an identifier.")
    refunded = ""
    if hasattr(payment, "get"):
        amount_refunded = payment.get("amountRefunded") or payment.get(
            "amount_refunded"
        )
        if hasattr(amount_refunded, "get"):
            refunded = str(amount_refunded.get("value") or "")
    material = "|".join((identifier, payment_status(payment), refunded))
    return sha256(material.encode("utf-8")).hexdigest()
