import uuid
from decimal import Decimal

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session

from app.api.v1.deps import require_role
from app.api.v1.endpoints.cart import _get_or_create_cart, _serialize_cart
from app.db.session import get_db
from app.models.branch import Branch
from app.models.cart import Cart, CartItem, CartItemOption
from app.models.group_order import (
    GroupOrderParticipant,
    GroupOrderSession,
    GroupOrderSessionStatus,
)
from app.models.menu import MenuItem
from app.models.menu_option import MenuItemOption
from app.models.order import (
    DeliveryMode,
    Order,
    OrderItem,
    OrderItemOption,
    OrderStatus,
    PaymentStatus,
)
from app.models.user import User, UserRole
from app.schemas.auth import MessageResponse
from app.schemas.group_order import (
    GroupOrderJoinRequest,
    GroupOrderLockRequest,
    GroupOrderLockResponse,
    GroupOrderParticipantOut,
    GroupOrderPayerResult,
    GroupOrderSessionDetailOut,
    GroupOrderSessionOut,
    GroupOrderSessionStartRequest,
)
from app.services import group_order_notifications as group_notifications
from app.services import group_orders as group_orders_service
from app.services import pricing as pricing_service
from app.services.branch_hours import is_branch_open
from app.services.payments import base as payment_base
from app.services.payments import registry as payment_registry

router = APIRouter(prefix="/cart/group-sessions", tags=["group-orders"])

_CENTS = Decimal("0.01")


def _session_detail(
    db: Session, session: GroupOrderSession
) -> GroupOrderSessionDetailOut:
    cart = db.query(Cart).filter(Cart.id == session.cart_id).first()
    participants = [
        GroupOrderParticipantOut(user_id=p.user_id, name=name, joined_at=p.joined_at)
        for p, name in db.query(GroupOrderParticipant, User.name)
        .join(User, User.id == GroupOrderParticipant.user_id)
        .filter(GroupOrderParticipant.session_id == session.id)
        .all()
    ]
    return GroupOrderSessionDetailOut(
        **GroupOrderSessionOut.model_validate(session).model_dump(),
        participants=participants,
        cart=_serialize_cart(db, cart),
    )


def _remove_participant_and_items(
    db: Session, session: GroupOrderSession, user_id: uuid.UUID
) -> None:
    """Shared by leave_session (self) and remove_participant (host) —
    drops both the roster row and anything that user personally added,
    same as clearing a solo cart down to empty would."""
    item_ids = [
        row.id
        for row in db.query(CartItem.id).filter(
            CartItem.cart_id == session.cart_id, CartItem.added_by_user_id == user_id
        )
    ]
    if item_ids:
        db.query(CartItemOption).filter(
            CartItemOption.cart_item_id.in_(item_ids)
        ).delete(synchronize_session=False)
        db.query(CartItem).filter(CartItem.id.in_(item_ids)).delete(
            synchronize_session=False
        )
    db.query(GroupOrderParticipant).filter(
        GroupOrderParticipant.session_id == session.id,
        GroupOrderParticipant.user_id == user_id,
    ).delete(synchronize_session=False)
    db.commit()

    remaining = db.query(CartItem).filter(CartItem.cart_id == session.cart_id).count()
    if remaining == 0:
        cart = db.query(Cart).filter(Cart.id == session.cart_id).first()
        if cart is not None:
            cart.branch_id = None
            db.commit()


@router.post("", response_model=GroupOrderSessionOut)
def start_session(
    payload: GroupOrderSessionStartRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> GroupOrderSessionOut:
    cart = _get_or_create_cart(db, current_user.id)
    if group_orders_service.get_active_session_for_cart(db, cart.id) is not None:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="You already have an active group order.",
        )

    # join_code collisions are extremely unlikely (32^6 combinations)
    # but the column is unique, so a short retry is cheap insurance
    # rather than a 500 on the rare hit.
    for _ in range(5):
        session = GroupOrderSession(
            cart_id=cart.id,
            host_id=current_user.id,
            join_code=group_orders_service.generate_join_code(),
            deadline=payload.deadline,
            per_person_limit=payload.per_person_limit,
        )
        db.add(session)
        try:
            db.commit()
        except IntegrityError:
            db.rollback()
            continue
        db.refresh(session)
        return GroupOrderSessionOut.model_validate(session)
    raise HTTPException(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        detail="Could not start a group order right now — try again.",
    )


@router.post("/join", response_model=GroupOrderSessionDetailOut)
def join_session(
    payload: GroupOrderJoinRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> GroupOrderSessionDetailOut:
    session = group_orders_service.get_session_by_join_code_or_404(
        db, payload.join_code
    )
    group_orders_service.require_open(session)
    if current_user.id == session.host_id:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="You're already hosting this group order.",
        )
    # Idempotent — re-scanning/re-submitting the same code after
    # already joining just returns the current state, not an error.
    if not group_orders_service.is_participant(db, session.id, current_user.id):
        db.add(GroupOrderParticipant(session_id=session.id, user_id=current_user.id))
        db.commit()
        group_notifications.notify_participant_joined(db, session, current_user.id)
    return _session_detail(db, session)


@router.get("/{session_id}", response_model=GroupOrderSessionDetailOut)
def get_session(
    session_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> GroupOrderSessionDetailOut:
    session = group_orders_service.get_session_or_404(db, session_id)
    group_orders_service.require_participant_or_host(db, session, current_user.id)
    return _session_detail(db, session)


@router.delete("/{session_id}/leave", response_model=MessageResponse)
def leave_session(
    session_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> MessageResponse:
    session = group_orders_service.get_session_or_404(db, session_id)
    if current_user.id == session.host_id:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="The host can't leave — cancel the group order instead.",
        )
    if session.status != GroupOrderSessionStatus.OPEN.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This group order is no longer open.",
        )
    group_orders_service.require_participant_or_host(db, session, current_user.id)
    _remove_participant_and_items(db, session, current_user.id)
    return MessageResponse(message="You left the group order.")


@router.delete("/{session_id}/participants/{user_id}", response_model=MessageResponse)
def remove_participant(
    session_id: uuid.UUID,
    user_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> MessageResponse:
    session = group_orders_service.get_session_or_404(db, session_id)
    group_orders_service.require_host(session, current_user.id)
    if session.status != GroupOrderSessionStatus.OPEN.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This group order is no longer open.",
        )
    if not group_orders_service.is_participant(db, session.id, user_id):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="That user isn't part of this group order.",
        )
    _remove_participant_and_items(db, session, user_id)
    group_notifications.notify_participant_removed(db, session, user_id)
    return MessageResponse(message="Participant removed.")


@router.post("/{session_id}/cancel", response_model=MessageResponse)
def cancel_session(
    session_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> MessageResponse:
    """Only while still OPEN — once locked, real Orders with their own
    payment attempts exist per participant, and those get cancelled
    individually via the normal app.api.v1.endpoints.orders order-
    cancellation flow, not by cancelling the session that produced
    them. Allowed even past the session's own deadline (see
    GroupOrderSession) — cancelling an already-lazily-expired session
    is exactly the cleanup action that should always be available."""
    session = group_orders_service.get_session_or_404(db, session_id)
    group_orders_service.require_host(session, current_user.id)
    if session.status != GroupOrderSessionStatus.OPEN.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This group order can no longer be cancelled.",
        )
    participant_ids = [
        row.user_id
        for row in db.query(GroupOrderParticipant.user_id).filter(
            GroupOrderParticipant.session_id == session.id
        )
    ]
    session.status = GroupOrderSessionStatus.CANCELLED.value
    db.commit()
    group_notifications.notify_session_cancelled(db, session, participant_ids)
    return MessageResponse(message="Group order cancelled.")


@router.post("/{session_id}/lock", response_model=GroupOrderLockResponse)
def lock_session(
    session_id: uuid.UUID,
    payload: GroupOrderLockRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> GroupOrderLockResponse:
    """Splits the shared cart into one real Order per person who added
    anything (plus the host even if they added nothing themselves,
    since they always cover delivery_fee/service_fee/vat) — each gets
    their own independent payment-provider checkout for just their own
    items. Only Chapa exists as a real provider today (see
    app.services.payments), so it's the only one used here; per-guest
    provider choice is a natural later addition once more exist, not
    something to build against a single option.

    No promo-code support here yet — deliberately out of scope for the
    first version: distributing one code's discount fairly across N
    independently-paying people raises the same "who actually benefits
    from it" question the payment split itself raises, and isn't worth
    solving until real usage shows it's needed.
    """
    session = group_orders_service.get_session_or_404(db, session_id)
    group_orders_service.require_host(session, current_user.id)
    group_orders_service.require_open(session)

    is_delivery = payload.delivery_mode == DeliveryMode.DELIVERY.value
    if is_delivery and not payload.delivery_address:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
            detail="Delivery address is required for delivery orders.",
        )
    if is_delivery and (
        payload.delivery_latitude is None or payload.delivery_longitude is None
    ):
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
            detail="Delivery location is required for delivery orders.",
        )

    cart = db.query(Cart).filter(Cart.id == session.cart_id).first()
    cart_items = (
        db.query(CartItem).filter(CartItem.cart_id == cart.id).all()
        if cart is not None
        else []
    )
    if cart is None or cart.branch_id is None or not cart_items:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Nothing's been added to this group order yet.",
        )

    branch = db.query(Branch).filter(Branch.id == cart.branch_id).first()
    if branch is not None and not is_branch_open(branch):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This branch is currently closed.",
        )

    snapshots_by_user: dict[
        uuid.UUID, list[tuple[CartItem, MenuItem, list[MenuItemOption], Decimal]]
    ] = {}
    for cart_item in cart_items:
        menu_item = (
            db.query(MenuItem)
            .filter(
                MenuItem.id == cart_item.menu_item_id, MenuItem.deleted_at.is_(None)
            )
            .first()
        )
        if menu_item is None:
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail="An item in this group order is no longer available.",
            )
        if not menu_item.is_available:
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail=f'"{menu_item.name}" is no longer available.',
            )
        selected_options = [
            option
            for _cio, option in db.query(CartItemOption, MenuItemOption)
            .join(
                MenuItemOption, MenuItemOption.id == CartItemOption.menu_item_option_id
            )
            .filter(CartItemOption.cart_item_id == cart_item.id)
            .all()
        ]
        for option in selected_options:
            if not option.is_available:
                raise HTTPException(
                    status_code=status.HTTP_409_CONFLICT,
                    detail=f'"{option.name}" is no longer available.',
                )
        options_total = sum((o.price_delta for o in selected_options), Decimal("0.00"))
        line_total = ((menu_item.price + options_total) * cart_item.quantity).quantize(
            _CENTS
        )
        snapshots_by_user.setdefault(cart_item.added_by_user_id, []).append(
            (cart_item, menu_item, selected_options, line_total)
        )
    # The host always gets an order, even if they never added an item
    # themselves — they're always the one covering delivery_fee/
    # service_fee/vat.
    snapshots_by_user.setdefault(session.host_id, [])

    combined_subtotal = sum(
        (
            line_total
            for items in snapshots_by_user.values()
            for *_, line_total in items
        ),
        Decimal("0.00"),
    )
    delivery_fee = (
        pricing_service.compute_delivery_fee(
            branch, payload.delivery_latitude, payload.delivery_longitude
        )
        if is_delivery
        else Decimal("0.00")
    )
    service_fee = pricing_service.compute_service_fee(combined_subtotal)
    vat = pricing_service.compute_vat(combined_subtotal + delivery_fee)

    provider = payment_registry.get_provider("chapa")

    payers: list[GroupOrderPayerResult] = []
    for user_id, items in snapshots_by_user.items():
        is_host = user_id == session.host_id
        user_subtotal = sum((lt for *_, lt in items), Decimal("0.00"))
        order_delivery_fee = delivery_fee if is_host else Decimal("0.00")
        order_service_fee = service_fee if is_host else Decimal("0.00")
        order_vat = vat if is_host else Decimal("0.00")
        order_total = user_subtotal + order_delivery_fee + order_service_fee + order_vat

        payer_user = db.query(User).filter(User.id == user_id).first()
        # Nothing to actually collect (host covering a takeaway order
        # they didn't add anything to themselves) — confirmed outright
        # rather than sending them through a real gateway for ETB 0.00.
        no_payment_due = order_total <= Decimal("0.00")

        order = Order(
            customer_id=user_id,
            branch_id=cart.branch_id,
            group_order_session_id=session.id,
            delivery_mode=payload.delivery_mode,
            delivery_address=payload.delivery_address if is_delivery else None,
            delivery_latitude=payload.delivery_latitude if is_delivery else None,
            delivery_longitude=payload.delivery_longitude if is_delivery else None,
            subtotal=user_subtotal,
            delivery_fee=order_delivery_fee,
            service_fee=order_service_fee,
            vat=order_vat,
            total=order_total,
            tx_ref=payment_base.generate_tx_ref(),
            status=OrderStatus.CONFIRMED.value
            if no_payment_due
            else OrderStatus.PENDING_PAYMENT.value,
            payment_status=PaymentStatus.PAID.value
            if no_payment_due
            else PaymentStatus.PENDING.value,
            payment_method=provider.PROVIDER_NAME,
        )
        db.add(order)
        db.commit()
        db.refresh(order)

        for cart_item, menu_item, selected_options, line_total in items:
            order_item = OrderItem(
                order_id=order.id,
                menu_item_id=menu_item.id,
                name_snapshot=menu_item.name,
                unit_price_snapshot=menu_item.price,
                quantity=cart_item.quantity,
                line_total=line_total,
                special_instructions=cart_item.special_instructions,
                added_by_user_id=cart_item.added_by_user_id,
            )
            db.add(order_item)
            db.commit()
            db.refresh(order_item)
            for option in selected_options:
                db.add(
                    OrderItemOption(
                        order_item_id=order_item.id,
                        menu_item_option_id=option.id,
                        name_snapshot=option.name,
                        price_delta_snapshot=option.price_delta,
                    )
                )
        db.commit()

        checkout_url = None
        if not no_payment_due:
            name_parts = payer_user.name.strip().split(" ", 1)
            first_name = name_parts[0]
            last_name = name_parts[1] if len(name_parts) > 1 else first_name
            checkout_url = provider.initialize_payment(
                tx_ref=order.tx_ref,
                amount=order.total,
                email=payer_user.email,
                first_name=first_name,
                last_name=last_name,
                phone_number=payer_user.phone.lstrip("+") if payer_user.phone else None,
            )
            order.chapa_checkout_url = checkout_url
            db.commit()
            db.refresh(order)

        payers.append(
            GroupOrderPayerResult(
                user_id=user_id,
                name=payer_user.name,
                is_host=is_host,
                order_id=order.id,
                amount=order.total,
                checkout_url=checkout_url,
            )
        )

    cart_item_ids = [ci.id for ci in cart_items]
    db.query(CartItemOption).filter(
        CartItemOption.cart_item_id.in_(cart_item_ids)
    ).delete(synchronize_session=False)
    db.query(CartItem).filter(CartItem.cart_id == cart.id).delete(
        synchronize_session=False
    )
    cart.branch_id = None
    db.commit()

    session.status = GroupOrderSessionStatus.LOCKED.value
    db.commit()
    db.refresh(session)

    group_notifications.notify_session_locked(
        db, session, [p.user_id for p in payers if not p.is_host]
    )

    return GroupOrderLockResponse(
        session=GroupOrderSessionOut.model_validate(session), payers=payers
    )


@router.post("/{session_id}/finalize", response_model=GroupOrderLockResponse)
def finalize_session(
    session_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> GroupOrderLockResponse:
    """The host's explicit "stop waiting for everyone" action, any time
    after locking — no automatic timer does this (see GroupOrderSession).
    Anyone who's paid is left untouched. Anyone who hasn't:

    - If the host's own order is still unpaid too, that guest's items
      get folded onto the host's order (added_by_user_id preserved, so
      the host can still see whose items they ended up covering) and
      their now-empty order is cancelled — the host's order total
      grows to include it, same amount the host is about to pay in one
      go.
    - If the host's own order has *already* been paid, absorbing more
      isn't possible — Chapa already collected a specific amount
      against that tx_ref, and silently growing the total afterward
      would make the order's total lie about what was actually
      charged. That guest's order is just cancelled; the host settles
      up with them directly, outside the app.

    Safe to call more than once, or when everyone's already paid —
    a no-op beyond marking the session CHECKED_OUT.
    """
    session = group_orders_service.get_session_or_404(db, session_id)
    group_orders_service.require_host(session, current_user.id)
    if session.status != GroupOrderSessionStatus.LOCKED.value:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This group order hasn't been locked yet.",
        )

    orders = db.query(Order).filter(Order.group_order_session_id == session.id).all()
    host_order = next((o for o in orders if o.customer_id == session.host_id), None)
    if host_order is None:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="This group order has no host order on record.",
        )
    host_can_absorb = host_order.payment_status != PaymentStatus.PAID.value

    absorbed_total = Decimal("0.00")
    for order in orders:
        if order.customer_id == session.host_id:
            continue
        if order.payment_status == PaymentStatus.PAID.value:
            continue  # already settled, leave it alone

        if host_can_absorb:
            items = db.query(OrderItem).filter(OrderItem.order_id == order.id).all()
            for item in items:
                options = (
                    db.query(OrderItemOption)
                    .filter(OrderItemOption.order_item_id == item.id)
                    .all()
                )
                new_item = OrderItem(
                    order_id=host_order.id,
                    menu_item_id=item.menu_item_id,
                    name_snapshot=item.name_snapshot,
                    unit_price_snapshot=item.unit_price_snapshot,
                    quantity=item.quantity,
                    line_total=item.line_total,
                    special_instructions=item.special_instructions,
                    added_by_user_id=item.added_by_user_id,
                )
                db.add(new_item)
                db.commit()
                db.refresh(new_item)
                for option in options:
                    db.add(
                        OrderItemOption(
                            order_item_id=new_item.id,
                            menu_item_option_id=option.menu_item_option_id,
                            name_snapshot=option.name_snapshot,
                            price_delta_snapshot=option.price_delta_snapshot,
                        )
                    )
                absorbed_total += item.line_total
            db.commit()

        order.status = OrderStatus.CANCELLED.value
        db.commit()

    if absorbed_total > 0:
        host_order.subtotal += absorbed_total
        host_order.total += absorbed_total
        # The checkout_url minted at lock time is now stale — Chapa
        # fixes the amount when that checkout session is created, so a
        # bigger total here means a genuinely new payment attempt, not
        # just a bigger number next to the same old link.
        host_order.tx_ref = payment_base.generate_tx_ref()
        db.commit()
        db.refresh(host_order)

        host_user = db.query(User).filter(User.id == host_order.customer_id).first()
        name_parts = host_user.name.strip().split(" ", 1)
        first_name = name_parts[0]
        last_name = name_parts[1] if len(name_parts) > 1 else first_name
        provider = payment_registry.get_provider(host_order.payment_method)
        host_order.chapa_checkout_url = provider.initialize_payment(
            tx_ref=host_order.tx_ref,
            amount=host_order.total,
            email=host_user.email,
            first_name=first_name,
            last_name=last_name,
            phone_number=host_user.phone.lstrip("+") if host_user.phone else None,
        )
        db.commit()
        db.refresh(host_order)

    session.status = GroupOrderSessionStatus.CHECKED_OUT.value
    db.commit()
    db.refresh(session)

    payers = [
        GroupOrderPayerResult(
            user_id=order.customer_id,
            name=(db.query(User).filter(User.id == order.customer_id).first()).name,
            is_host=order.customer_id == session.host_id,
            order_id=order.id,
            amount=order.total,
            checkout_url=order.chapa_checkout_url,
        )
        for order in orders
        if order.status != OrderStatus.CANCELLED.value
    ]
    return GroupOrderLockResponse(
        session=GroupOrderSessionOut.model_validate(session), payers=payers
    )
