from decimal import Decimal
from urllib.parse import quote

from app.models.enums import PaymentStatus


def update_payment_summary(total_commission: Decimal, total_paid: Decimal) -> tuple[Decimal, Decimal, PaymentStatus]:
    pending = total_commission - total_paid
    if pending <= 0:
        status = PaymentStatus.PAID
        pending = Decimal("0.00")
    elif total_paid > 0:
        status = PaymentStatus.PARTIAL
    else:
        status = PaymentStatus.PENDING
    return pending, total_paid, status


def build_whatsapp_url(mobile: str, message: str) -> str:
    clean_mobile = normalize_whatsapp_recipient(mobile)
    return f"https://wa.me/{clean_mobile}?text={quote(message)}"


def normalize_whatsapp_recipient(mobile: str) -> str:
    clean_mobile = "".join(ch for ch in mobile if ch.isdigit())
    if len(clean_mobile) == 10:
        clean_mobile = f"91{clean_mobile}"
    return clean_mobile


def build_renewal_message(
    customer_name: str,
    policy_type: str | None,
    policy_number: str | None,
    vehicle_number: str | None,
    expiry_date: str,
    agency_name: str,
) -> str:
    policy_type_text = policy_type or "insurance"
    policy_number_text = policy_number or "N/A"
    vehicle_text = vehicle_number or "N/A"
    return (
        f"Dear {customer_name}, your {policy_type_text} insurance policy ({policy_number_text}) "
        f"for vehicle {vehicle_text} is expiring on {expiry_date}. "
        f"Please contact us for renewal. — {agency_name}"
    )
