import hashlib
import secrets

from django.conf import settings

from haso_payment.exceptions import PaymentFlowException


def generate_salt(*, length: int = 10):
    length = abs(length if length > 0 else 10)
    salt = secrets.token_hex(length * 3)
    return salt if not length else salt[:length]


def generate_hash(*, salt: str, session_id: str, hash_key: str = None):
    if not hash_key:
        raise PaymentFlowException("Hash key is required to generate hash.")
    return hashlib.sha512(
        f"{salt}|{session_id}|{hash_key}".encode("utf-8")
    ).hexdigest()


def get_extension_conf(*, payment_option_slug: str):
    configs = getattr(settings, "HASO_EXTENSION_CONF", {})
    config = configs.get(payment_option_slug) or configs.get("default") or {}

    if any([
        not config,
        not config.get("extension_url"),
        not config.get("hash_key"),
    ]):
        raise PaymentFlowException("Extension configuration not found.")

    return config


def get_deps(*, session_id: str, payment_option_slug: str):
    salt = generate_salt(length=10)
    config = get_extension_conf(payment_option_slug=payment_option_slug)
    hash = generate_hash(
        salt=salt, session_id=session_id, hash_key=config.get("hash_key")
    )
    extension_url = config.get("extension_url")

    return salt, hash, extension_url
