import decimal


def get_product_version_price_with_discount(
    *, coupon_version, product_version, CouponEligibility
):
    """
    Determine the new discounted price for a product after the coupon discount is applied

    This is copied from a similar function from ecommerce.api so we can make sure this function remains the same
    while the other one can change without affecting migrations.

    Args:
        coupon_version (CouponVersion): the CouponVersion object
        product_version (ProductVersion): the ProductVersion object
        apps (any): The apps argument from the RunPython function

    Returns:
        Decimal: the discounted price for the Product
    """
    price = product_version.price
    if (
        coupon_version
        and CouponEligibility.objects.filter(
            coupon__versions=coupon_version, product__productversions=product_version
        ).exists()
    ):
        discount = (coupon_version.payment_version.amount * price).quantize(
            decimal.Decimal("0.01"), rounding=decimal.ROUND_HALF_UP
        )
    else:
        discount = 0
    return price - discount