import uuid

from sqlalchemy.orm import Session

from app.models.group_order import GroupOrderSession
from app.models.user import User
from app.services import push as push_service


def _name(db: Session, user_id: uuid.UUID) -> str:
    user = db.query(User).filter(User.id == user_id).first()
    return user.name if user is not None else "Someone"


def notify_participant_joined(
    db: Session, session: GroupOrderSession, participant_id: uuid.UUID
) -> None:
    """Push-only, to the host — everyone's expected to be together in
    person for a group order (see GroupOrderSession's docstring), so
    this is a "heads up, they're in" nudge, not something that needs
    SMS's guaranteed-delivery reach the way an unregistered gift
    recipient does (see app.services.order_notifications)."""
    push_service.notify_user(
        db,
        session.host_id,
        title="Someone joined your group order",
        body=f"{_name(db, participant_id)} joined — they can add items now.",
        data={"type": "group_order_joined", "session_id": str(session.id)},
    )


def notify_participant_removed(
    db: Session, session: GroupOrderSession, removed_user_id: uuid.UUID
) -> None:
    push_service.notify_user(
        db,
        removed_user_id,
        title="Removed from group order",
        body="The host removed you from the group order.",
        data={"type": "group_order_removed", "session_id": str(session.id)},
    )


def notify_session_locked(
    db: Session,
    session: GroupOrderSession,
    payer_ids_excluding_host: list[uuid.UUID],
) -> None:
    """Fires once, right after lock_session splits the cart and mints
    each payer's own checkout — the checkout_url itself isn't in the
    push payload (recipients differ per person; the app already knows
    its own session_id and can fetch app.api.v1.endpoints.group_orders.
    get_session for the up-to-date checkout link rather than trusting
    a URL baked into a notification that could go stale)."""
    for user_id in payer_ids_excluding_host:
        push_service.notify_user(
            db,
            user_id,
            title="Time to pay for your order",
            body="The host locked the group order — pay for your items now.",
            data={"type": "group_order_locked", "session_id": str(session.id)},
        )


def notify_session_cancelled(
    db: Session, session: GroupOrderSession, participant_ids: list[uuid.UUID]
) -> None:
    for user_id in participant_ids:
        push_service.notify_user(
            db,
            user_id,
            title="Group order cancelled",
            body="The host cancelled this group order.",
            data={"type": "group_order_cancelled", "session_id": str(session.id)},
        )
