from decimal import ROUND_HALF_UP, Decimal

from app.core.config import settings
from app.models.branch import Branch
from app.models.promo_code import DiscountType, PromoCode
from app.utils.geo import haversine_km

_CENTS = Decimal("0.01")


def compute_delivery_fee(
    branch: Branch, delivery_latitude: float, delivery_longitude: float
) -> Decimal:
    """base + per_km * distance, distance from the branch to the
    delivery address. Zero for takeaway orders — callers just don't
    call this in that case (see app.api.v1.endpoints.orders.checkout)."""
    distance_km = Decimal(
        str(
            haversine_km(
                branch.latitude, branch.longitude, delivery_latitude, delivery_longitude
            )
        )
    )
    fee = settings.delivery_fee_base + distance_km * settings.delivery_fee_per_km
    return fee.quantize(_CENTS, rounding=ROUND_HALF_UP)


def compute_service_fee(subtotal: Decimal) -> Decimal:
    """A percentage of the food subtotal, on every order regardless of
    delivery_mode — a platform/payment-processing charge, not a
    delivery cost. The legacy system had no equivalent of this."""
    return (subtotal * settings.service_fee_rate).quantize(
        _CENTS, rounding=ROUND_HALF_UP
    )


def compute_vat(taxable_amount: Decimal) -> Decimal:
    """taxable_amount is subtotal + delivery_fee, matching the legacy
    formula exactly (confirmed from its order-computation code) —
    service_fee is deliberately not part of the taxable base, since
    it's a new line the legacy VAT calculation never accounted for."""
    return (taxable_amount * settings.vat_rate).quantize(_CENTS, rounding=ROUND_HALF_UP)


def compute_discount(promo: PromoCode, subtotal: Decimal) -> Decimal:
    """Raw discount off subtotal, before the merchant-vs-platform
    funding cap in app.api.v1.endpoints.orders.checkout is applied —
    percentage of subtotal (capped by max_discount_amount) or a flat
    ETB amount. Capped at subtotal either way: a merchant-funded code
    can't discount more than the food itself costs (see checkout for
    the platform-funded case, which is capped at service_fee
    instead)."""
    if promo.discount_type == DiscountType.PERCENTAGE.value:
        discount = subtotal * (promo.discount_value / Decimal("100"))
        if promo.max_discount_amount is not None:
            discount = min(discount, promo.max_discount_amount)
    else:
        discount = promo.discount_value
    discount = min(discount, subtotal)
    return discount.quantize(_CENTS, rounding=ROUND_HALF_UP)
