import hashlib
import hmac
import json
from decimal import Decimal

import requests
from django.conf import settings


class AuthorizeNetError(RuntimeError):
    pass


def _post(payload):
    response = requests.post(settings.AUTHNET_API_URL, json=payload, timeout=(5, 20))
    response.raise_for_status()
    data = json.loads(response.content.decode("utf-8-sig"))
    messages = data.get("messages", {})
    if messages.get("resultCode") != "Ok":
        detail = "; ".join(item.get("text", "Unknown error") for item in messages.get("message", []))
        raise AuthorizeNetError(detail or "Authorize.Net rejected the request.")
    return data


def hosted_payment_token(order, return_url, cancel_url):
    if not settings.AUTHNET_ENABLED:
        raise AuthorizeNetError("Authorize.Net is disabled.")
    if not settings.AUTHNET_API_LOGIN_ID or not settings.AUTHNET_TRANSACTION_KEY:
        raise AuthorizeNetError("Authorize.Net credentials are not configured.")
    transaction = {
        "transactionType": "authCaptureTransaction",
        "amount": str(Decimal(order.total).quantize(Decimal("0.01"))),
        "order": {"invoiceNumber": order.authnet_invoice, "description": "Grind Golf order"},
        "customer": {"email": order.email},
        "billTo": {
            "firstName": order.first_name, "lastName": order.last_name,
            "address": order.address1, "city": order.city, "state": order.state,
            "zip": order.postal_code, "country": order.country,
        },
    }
    payload = {"getHostedPaymentPageRequest": {
        "merchantAuthentication": {
            "name": settings.AUTHNET_API_LOGIN_ID,
            "transactionKey": settings.AUTHNET_TRANSACTION_KEY,
        },
        "transactionRequest": transaction,
        "hostedPaymentSettings": {"setting": [
            {"settingName": "hostedPaymentReturnOptions", "settingValue": json.dumps({
                "showReceipt": False, "url": return_url, "urlText": "Return to Grind Golf",
                "cancelUrl": cancel_url, "cancelUrlText": "Cancel",
            })},
            {"settingName": "hostedPaymentButtonOptions", "settingValue": json.dumps({"text": "Pay securely"})},
            {"settingName": "hostedPaymentOrderOptions", "settingValue": json.dumps({"show": True})},
            {"settingName": "hostedPaymentCustomerOptions", "settingValue": json.dumps({"showEmail": False, "requiredEmail": True})},
        ]},
    }}
    return _post(payload)["token"]


def transaction_details(transaction_id):
    payload = {"getTransactionDetailsRequest": {
        "merchantAuthentication": {
            "name": settings.AUTHNET_API_LOGIN_ID,
            "transactionKey": settings.AUTHNET_TRANSACTION_KEY,
        },
        "transId": str(transaction_id),
    }}
    return _post(payload).get("transaction", {})


def valid_webhook_signature(raw_body, header):
    if not settings.AUTHNET_SIGNATURE_KEY or not header:
        return False
    supplied = header.split("=", 1)[-1].strip().lower()
    try:
        key = bytes.fromhex(settings.AUTHNET_SIGNATURE_KEY.strip())
    except ValueError:
        return False
    expected = hmac.new(key, raw_body, hashlib.sha512).hexdigest().lower()
    return hmac.compare_digest(expected, supplied)
