from decimal import Decimal, ROUND_HALF_UP
import stripe
from mama_care_api import settings

stripe.api_key = settings.STRIPE_SECRET_KEY

ZERO_DECIMAL_CURRENCIES = {
    "bif",
    "clp",
    "djf",
    "gnf",
    "jpy",
    "kmf",
    "krw",
    "mga",
    "pyg",
    "rwf",
    "ugx",
    "vnd",
    "vuv",
    "xaf",
    "xof",
    "xpf",
}

THREE_DECIMAL_CURRENCIES = {
    "bhd",
    "iqd",
    "jod",
    "kwd",
    "lyd",
    "omr",
    "tnd",
}


def to_smallest_unit(amount, currency):
    currency = currency.lower()

    amount = Decimal(str(amount))

    if currency in ZERO_DECIMAL_CURRENCIES:
        return int(amount.quantize(Decimal("1"), rounding=ROUND_HALF_UP))

    elif currency in THREE_DECIMAL_CURRENCIES:
        return int(
            (amount * Decimal("1000"))
            .quantize(Decimal("1"), rounding=ROUND_HALF_UP)
        )

    else:
        return int(
            (amount * Decimal("100"))
            .quantize(Decimal("1"), rounding=ROUND_HALF_UP)
        )

def create_payment_intent(amount,orderId, currency="gbp"):
    intent = stripe.PaymentIntent.create(
    amount=to_smallest_unit(amount, currency),
    currency=currency.lower(),
        automatic_payment_methods={
            "enabled": True,
        },
        metadata={
            "order_id": orderId,
        },
    )

    return {
        "orderId": orderId,
        "paymentIntentId": intent.id,
        "clientSecret": intent.client_secret,
        "amount": intent.amount,
        "currency": intent.currency,
        "status": intent.status,
    }