def notify_order_completed(order):
    """Notify the customer when an order is marked completed."""
    from app_server.api.routes import (
        send_sms_notification,
        send_whatsapp_notification,
    )

    formatted_phone = order.customer_phone
    if formatted_phone and not formatted_phone.startswith("+"):
        formatted_phone = "+92" + formatted_phone.lstrip("0")

    if not formatted_phone:
        return

    message = (
        f"Assalam-o-Alaikum {order.customer_name}! "
        f"Aapka Order #{order.id} SwiftCart se Approve ho gaya hai aur ship kar diya gaya hai. "
        f"Shukriya!"
    )
    send_sms_notification(formatted_phone, message, order.id)
    send_whatsapp_notification(formatted_phone, message, order.id)


def apply_order_status_update(order, new_status):
    previous_status = order.status
    order.status = new_status
    if new_status == "Completed" and previous_status != "Completed":
        notify_order_completed(order)
