"""
iPay Africa payment utility.

Docs: https://dev.ipayafrica.com/
Payment gateway URL: https://payments.ipayafrica.com/v3/ke
"""
import hashlib
import hmac
from django.conf import settings


IPAY_GATEWAY_URL = "https://payments.ipayafrica.com/v3/ke"


def _hmac_md5(key: str, data: str) -> str:
    return hmac.new(
        key.encode('utf-8'),
        data.encode('utf-8'),
        hashlib.md5
    ).hexdigest()


def build_payment_params(order, callback_url: str) -> dict:
    """
    Build the GET parameters needed to redirect the customer to iPay.
    Returns a dict; the view turns it into a redirect URL.
    """
    live     = "1" if settings.IPAY_LIVE else "0"
    oid      = str(order.id)
    inv      = str(order.id)
    ttl      = f"{order.total_price:.2f}"
    tel      = order.phone
    eml      = order.email
    vid      = settings.IPAY_VENDOR_ID
    curr     = "KES"
    p1       = f"Nutrientz Order #{order.id}"
    p2       = ""
    p3       = ""
    p4       = ""
    cbk      = callback_url
    cst      = f"{order.first_name} {order.last_name}".strip()
    crl      = "0"

    # Hash string — order matters, per iPay specification
    datastring = (
        live + oid + inv + ttl + tel + eml
        + vid + curr + p1 + p2 + p3 + p4
        + cbk + cst + crl
    )
    hsh = _hmac_md5(settings.IPAY_HASH_KEY, datastring)

    return {
        "live": live,
        "oid":  oid,
        "inv":  inv,
        "ttl":  ttl,
        "tel":  tel,
        "eml":  eml,
        "vid":  vid,
        "curr": curr,
        "p1":   p1,
        "p2":   p2,
        "p3":   p3,
        "p4":   p4,
        "cbk":  cbk,
        "cst":  cst,
        "crl":  crl,
        "hsh":  hsh,
    }


def verify_callback(post_data: dict) -> bool:
    """
    Verify the hash sent back by iPay in the payment callback.
    Returns True if the hash is valid (payment is authentic).
    """
    live   = "1" if settings.IPAY_LIVE else "0"
    status = post_data.get("status", "")
    oid    = post_data.get("oid", "")
    inv    = post_data.get("inv", "")
    ttl    = post_data.get("ttl", "")
    tel    = post_data.get("tel", "")
    eml    = post_data.get("eml", "")
    vid    = post_data.get("vid", "")
    curr   = post_data.get("curr", "")
    p1     = post_data.get("p1", "")
    p2     = post_data.get("p2", "")
    p3     = post_data.get("p3", "")
    p4     = post_data.get("p4", "")
    cbk    = post_data.get("cbk", "")
    cst    = post_data.get("cst", "")
    crl    = post_data.get("crl", "0")
    received_hash = post_data.get("hash", "")

    datastring = (
        live + status + oid + inv + ttl + tel + eml
        + vid + curr + p1 + p2 + p3 + p4
        + cbk + cst + crl
    )
    expected_hash = _hmac_md5(settings.IPAY_HASH_KEY, datastring)
    return hmac.compare_digest(expected_hash, received_hash)


# iPay callback status codes
IPAY_STATUS_SUCCESS = "aei7p7yrx4ae34"
IPAY_STATUS_FAILED  = "fe2707etr5s4wq"
