import uuid
from decimal import Decimal

from sqlalchemy import func
from sqlalchemy.orm import Session

from app.models.promo_code import PromoCode, PromoCodeRedemption
from app.utils.time import utcnow


class PromoCodeError(Exception):
    """A promo code couldn't be applied as submitted — message is
    user-facing."""


def validate_promo_code(
    db: Session,
    code: str,
    merchant_id: uuid.UUID,
    branch_id: uuid.UUID,
    customer_id: uuid.UUID,
    subtotal: Decimal,
) -> PromoCode:
    """Every reason a code can't be used right now, for this customer,
    on this order. Raises PromoCodeError with a user-facing message on
    the first failure; returns the PromoCode row on success. Doesn't
    mutate anything — see redeem_promo_code for actually consuming it,
    called separately once the order this code applies to actually
    exists."""
    promo = (
        db.query(PromoCode)
        .filter(func.upper(PromoCode.code) == code.strip().upper())
        .first()
    )
    if promo is None or not promo.is_active:
        raise PromoCodeError("Invalid promo code.")
    if promo.merchant_id is not None and promo.merchant_id != merchant_id:
        raise PromoCodeError("This promo code isn't valid for this merchant.")
    if promo.branch_id is not None and promo.branch_id != branch_id:
        raise PromoCodeError("This promo code isn't valid for this branch.")

    now = utcnow()
    if promo.valid_from is not None and now < promo.valid_from:
        raise PromoCodeError("This promo code isn't active yet.")
    if promo.valid_until is not None and now > promo.valid_until:
        raise PromoCodeError("This promo code has expired.")

    if promo.min_order_amount is not None and subtotal < promo.min_order_amount:
        raise PromoCodeError(
            f"This promo code needs a minimum order of {promo.min_order_amount} ETB."
        )

    if promo.usage_limit is not None and promo.times_used >= promo.usage_limit:
        raise PromoCodeError("This promo code has reached its usage limit.")

    if promo.usage_limit_per_customer is not None:
        customer_uses = (
            db.query(PromoCodeRedemption)
            .filter(
                PromoCodeRedemption.promo_code_id == promo.id,
                PromoCodeRedemption.customer_id == customer_id,
            )
            .count()
        )
        if customer_uses >= promo.usage_limit_per_customer:
            raise PromoCodeError("You've already used this promo code.")

    return promo


def redeem_promo_code(
    db: Session,
    promo: PromoCode,
    customer_id: uuid.UUID,
    order_id: uuid.UUID,
    discount_amount: Decimal,
) -> None:
    """Records the redemption and increments times_used — called once
    the order this discount applies to has actually been created and
    committed, never speculatively during validation."""
    db.add(
        PromoCodeRedemption(
            promo_code_id=promo.id,
            customer_id=customer_id,
            order_id=order_id,
            discount_amount=discount_amount,
        )
    )
    promo.times_used += 1
    db.commit()


def reverse_redemption(db: Session, order_id: uuid.UUID) -> None:
    """Undoes redeem_promo_code — called when a cancelled order's
    discount is being fully refunded (see
    app.api.v1.endpoints.orders._cancel_order), so the customer never
    actually kept a discount they didn't end up paying for. A no-op if
    this order never redeemed a code."""
    redemption = (
        db.query(PromoCodeRedemption)
        .filter(PromoCodeRedemption.order_id == order_id)
        .first()
    )
    if redemption is None:
        return
    promo = db.query(PromoCode).filter(PromoCode.id == redemption.promo_code_id).first()
    db.delete(redemption)
    if promo is not None and promo.times_used > 0:
        promo.times_used -= 1
    db.commit()
