from sqlalchemy.orm import Session

from app.core.config import settings
from app.models.branch import Branch
from app.models.branch_manager import BranchManager
from app.models.delivery import DeliveryAssignment
from app.models.merchant import Merchant
from app.models.order import DeliveryMode, Order, OrderItem, OrderStatus
from app.models.user import User
from app.services import push as push_service
from app.services import sms as sms_service
from app.services.email import send_templated_email

# Bodies for the statuses app.api.v1.endpoints.orders.update_order_status
# can actually reach (see _VALID_TRANSITIONS there) — CONFIRMED and
# PENDING_PAYMENT never flow through that endpoint, so they're not here.
_STATUS_BODIES = {
    OrderStatus.PREPARING.value: "Your order is being prepared.",
    OrderStatus.READY.value: "Your order is ready.",
    OrderStatus.COMPLETED.value: "Your order is complete. Enjoy!",
    OrderStatus.CANCELLED.value: "Your order was cancelled.",
}


def _branch_staff_ids(db: Session, branch: Branch) -> set:
    staff_ids = set()
    merchant = db.query(Merchant).filter(Merchant.id == branch.merchant_id).first()
    if merchant is not None:
        staff_ids.add(merchant.owner_id)
    manager_ids = db.query(BranchManager.user_id).filter(
        BranchManager.branch_id == branch.id
    )
    staff_ids.update(uid for (uid,) in manager_ids)
    return staff_ids


def _notify_gift_recipient(db: Session, order: Order, branch_name: str) -> None:
    """ "Order for a Friend" — SMS always fires, since the recipient may
    not have (or be signed into) the app; it's the one channel
    guaranteed to reach them regardless. If recipient_phone also
    matches a registered account, they additionally get a push
    notification — free, and likely to land before the SMS does — on
    top of, not instead of, the SMS. Sent once, at confirmation, not
    on every later status change — the recipient wants "this is
    coming" up front, not a running play-by-play a real customer
    tracking their own order would want.

    Deliberately not framed as a "surprise" — the sender and recipient
    may well have already arranged this between themselves, so the
    copy doesn't presume it's a secret.

    Says "to be delivered", not "on its way" — this fires the moment
    the order is CONFIRMED (same trigger as notify_order_confirmed
    above), before the branch has even started preparing it, let
    alone before a courier has been dispatched. "On its way" would
    overstate how far along the order actually is at this point.

    An unregistered recipient also gets nudged to install the app
    (when app_download_url is actually configured — see
    app.core.config) rather than just being told an order is coming
    with no way to see anything about it. A registered recipient
    already has the app, so that line would be noise for them."""
    sender = db.query(User).filter(User.id == order.customer_id).first()
    sender_name = sender.name if sender is not None else "Someone"

    recipient_account = (
        db.query(User).filter(User.phone == order.recipient_phone).first()
    )

    sms_message = (
        f"Dear {order.recipient_name}, congratulations! You've received an "
        f"order from {sender_name} via Yeneb ({branch_name}), to be "
        f"delivered to {order.delivery_address}."
    )
    if recipient_account is None and settings.app_download_url:
        sms_message += (
            f" Get the Yeneb app to follow your orders: {settings.app_download_url}"
        )
    sms_service.send_sms(order.recipient_phone, sms_message)

    if recipient_account is not None:
        push_service.notify_user(
            db,
            recipient_account.id,
            title="Congratulations, you've received an order!",
            body=f"{sender_name} sent you an order from Yeneb ({branch_name}).",
            data={"type": "gift_order_incoming", "order_id": str(order.id)},
        )


def _send_order_confirmation_email(db: Session, order: Order, branch_name: str) -> None:
    """No-op if the paying customer has no email on file — plenty
    sign up by phone only (see CustomerSignupRequest), and this is a
    nice-to-have alongside the push/SMS notifications above, not
    something every order depends on landing."""
    customer = db.query(User).filter(User.id == order.customer_id).first()
    if customer is None or not customer.email:
        return

    is_delivery = order.delivery_mode == DeliveryMode.DELIVERY.value
    if is_delivery:
        eta_label = "Estimated delivery"
        eta_text = (
            f"{settings.delivery_eta_min_minutes}–"
            f"{settings.delivery_eta_max_minutes} min"
        )
    else:
        eta_label = "Ready for pickup in"
        eta_text = (
            f"{settings.pickup_eta_min_minutes}–{settings.pickup_eta_max_minutes} min"
        )

    items = db.query(OrderItem).filter(OrderItem.order_id == order.id).all()
    send_templated_email(
        customer.email,
        f"Order confirmed — {branch_name}",
        "order_confirmation",
        {
            "name": customer.name,
            "branch_name": branch_name,
            "eta_label": eta_label,
            "eta_text": eta_text,
            "items": [
                {
                    "name": item.name_snapshot,
                    "quantity": item.quantity,
                    "line_total": item.line_total,
                }
                for item in items
            ],
            "subtotal": order.subtotal,
            "delivery_fee": order.delivery_fee,
            "service_fee": order.service_fee,
            "vat": order.vat,
            "discount_amount": order.discount_amount,
            "total": order.total,
            "delivery_address": order.delivery_address if is_delivery else None,
        },
    )


def notify_order_confirmed(db: Session, order: Order) -> None:
    """Called once an order actually becomes CONFIRMED — from the cash
    branch of app.api.v1.endpoints.orders.checkout, and from the
    Chapa-success branch of app.api.v1.endpoints.payments.chapa_webhook.
    Never fires for a Chapa order still sitting at PENDING_PAYMENT, so
    a branch is never notified about an order that might still fail to
    pay."""
    branch = db.query(Branch).filter(Branch.id == order.branch_id).first()
    branch_name = branch.name if branch is not None else "the merchant"

    push_service.notify_user(
        db,
        order.customer_id,
        title="Order confirmed",
        body=f"Your order from {branch_name} has been confirmed.",
        data={"type": "order_confirmed", "order_id": str(order.id)},
    )
    _send_order_confirmation_email(db, order, branch_name)

    if order.recipient_name and order.recipient_phone:
        _notify_gift_recipient(db, order, branch_name)

    if branch is None:
        return
    for staff_id in _branch_staff_ids(db, branch):
        push_service.notify_user(
            db,
            staff_id,
            title="New order",
            body=f"A new order has come in for {branch_name}.",
            data={"type": "new_order", "order_id": str(order.id)},
        )


def notify_order_status_changed(db: Session, order: Order) -> None:
    body = _STATUS_BODIES.get(order.status)
    if body is None:
        return
    push_service.notify_user(
        db,
        order.customer_id,
        title="Order update",
        body=body,
        data={
            "type": "order_status",
            "order_id": str(order.id),
            "status": order.status,
        },
    )


def notify_branch_of_cancellation(db: Session, order: Order) -> None:
    """Called from app.api.v1.endpoints.orders._cancel_order — the
    generic notify_order_status_changed above already tells the
    customer their order was cancelled, but a branch that was already
    told about the order (see notify_order_confirmed) needs to hear
    about the cancellation too, regardless of whether it was the
    customer or the branch's own staff who triggered it."""
    branch = db.query(Branch).filter(Branch.id == order.branch_id).first()
    if branch is None:
        return
    for staff_id in _branch_staff_ids(db, branch):
        push_service.notify_user(
            db,
            staff_id,
            title="Order cancelled",
            body=f"An order for {branch.name} was cancelled.",
            data={"type": "order_cancelled", "order_id": str(order.id)},
        )


def notify_delivery_cancelled(db: Session, assignment: DeliveryAssignment) -> None:
    push_service.notify_user(
        db,
        assignment.courier_id,
        title="Delivery cancelled",
        body="This delivery was cancelled — no need to continue.",
        data={"type": "delivery_cancelled", "assignment_id": str(assignment.id)},
    )


def notify_delivery_offered(db: Session, assignment: DeliveryAssignment) -> None:
    push_service.notify_user(
        db,
        assignment.courier_id,
        title="New delivery offer",
        body="A new delivery is available near you.",
        data={"type": "delivery_offered", "assignment_id": str(assignment.id)},
    )


def _notify_customer_for_assignment(
    db: Session, assignment: DeliveryAssignment, title: str, body: str, event: str
) -> None:
    order = db.query(Order).filter(Order.id == assignment.order_id).first()
    if order is None:
        return
    push_service.notify_user(
        db,
        order.customer_id,
        title=title,
        body=body,
        data={"type": event, "order_id": str(order.id)},
    )


def notify_delivery_accepted(db: Session, assignment: DeliveryAssignment) -> None:
    _notify_customer_for_assignment(
        db,
        assignment,
        "Courier on the way",
        "A courier has accepted your delivery.",
        "delivery_accepted",
    )


def notify_delivery_picked_up(db: Session, assignment: DeliveryAssignment) -> None:
    _notify_customer_for_assignment(
        db,
        assignment,
        "Order picked up",
        "Your courier has picked up your order.",
        "delivery_picked_up",
    )


def notify_delivery_completed(db: Session, assignment: DeliveryAssignment) -> None:
    _notify_customer_for_assignment(
        db,
        assignment,
        "Order delivered",
        "Your order has been delivered. Enjoy your meal!",
        "delivery_completed",
    )
