import uuid

import redis as redis_lib
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import or_
from sqlalchemy.orm import Session

from app.api.v1.deps import get_current_user, require_role
from app.api.v1.endpoints.merchants import (
    _branch_out,
    _distance_expr,
    _public_all_branches_key,
    invalidate_public_caches,
)
from app.core.config import settings
from app.db.redis import get_redis
from app.db.session import get_db
from app.models.branch import Branch, BranchApprovalStatus
from app.models.branch_manager import BranchManager
from app.models.grocery import GroceryItemDetails
from app.models.menu import MenuCategory, MenuItem
from app.models.menu_option import MenuItemOption, MenuItemOptionGroup
from app.models.merchant import Merchant
from app.models.otp import OTPPurpose
from app.models.review import Review
from app.models.user import User, UserRole
from app.schemas.auth import InviteResponse, PhoneAndNameRequest, UserOut
from app.schemas.branch import (
    BranchApproveRequest,
    BranchHoursUpdateRequest,
    BranchMinimumOrderUpdateRequest,
    BranchOut,
    BranchUpdateRequest,
    BranchWithMenuOut,
)
from app.schemas.menu import (
    MenuCategoryCreateRequest,
    MenuCategoryOut,
    MenuCategoryUpdateRequest,
    MenuCategoryWithItemsOut,
    MenuItemCreateRequest,
    MenuItemOut,
    MenuItemUpdateRequest,
    MenuItemWithOptionsOut,
)
from app.schemas.menu_option import (
    MenuItemOptionCreateRequest,
    MenuItemOptionGroupCreateRequest,
    MenuItemOptionGroupOut,
    MenuItemOptionGroupUpdateRequest,
    MenuItemOptionGroupWithOptionsOut,
    MenuItemOptionOut,
    MenuItemOptionUpdateRequest,
)
from app.schemas.review import ReviewOut
from app.services import favorites as favorites_service
from app.services import otp as otp_service
from app.services import reviews as reviews_service
from app.services.branch_hours import is_branch_open
from app.services.cache import cache_delete, cache_get, cache_set
from app.services.favorites import get_favorited_branch_ids
from app.services.reviews import get_branch_rating_stats
from app.utils.time import utcnow

router = APIRouter(prefix="/branches", tags=["branches"])


def _branch_key(branch_id: uuid.UUID) -> str:
    return f"cache:branch:{branch_id}"


_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPERADMIN.value}
_NOT_FOUND = HTTPException(
    status_code=status.HTTP_404_NOT_FOUND, detail="Branch not found."
)
_ACCOUNT_EXISTS = HTTPException(
    status_code=status.HTTP_409_CONFLICT,
    detail="An account with this phone number already exists.",
)
_EMAIL_EXISTS = HTTPException(
    status_code=status.HTTP_409_CONFLICT,
    detail="An account with this email already exists.",
)


def _get_branch_and_merchant(
    db: Session, branch_id: uuid.UUID
) -> tuple[Branch, Merchant]:
    branch = (
        db.query(Branch)
        .filter(Branch.id == branch_id, Branch.deleted_at.is_(None))
        .first()
    )
    if branch is None:
        raise _NOT_FOUND
    merchant = db.query(Merchant).filter(Merchant.id == branch.merchant_id).first()
    return branch, merchant


def _is_owner(merchant: Merchant | None, current_user: User) -> bool:
    return merchant is not None and merchant.owner_id == current_user.id


def _is_branch_manager(db: Session, branch: Branch, current_user: User) -> bool:
    if current_user.role != UserRole.MANAGER.value:
        return False
    return (
        db.query(BranchManager)
        .filter(
            BranchManager.branch_id == branch.id,
            BranchManager.user_id == current_user.id,
        )
        .first()
        is not None
    )


def _visible_to_public(branch: Branch) -> bool:
    return (
        branch.approval_status == BranchApprovalStatus.APPROVED.value
        and branch.is_active
    )


def _get_visible_branch(
    db: Session, branch_id: uuid.UUID, current_user: User
) -> tuple[Branch, Merchant]:
    """Same visibility rule as list_branches: admins see everything, the
    owner and any manager assigned to this branch always see it, everyone
    else only sees approved + active branches. Not visible -> 404 rather
    than 403, so its existence/status isn't leaked."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    is_admin = current_user.role in _ADMIN_ROLES
    if not (
        is_admin
        or _is_owner(merchant, current_user)
        or _is_branch_manager(db, branch, current_user)
        or _visible_to_public(branch)
    ):
        raise _NOT_FOUND
    return branch, merchant


def _require_branch_staff(
    db: Session, branch: Branch, merchant: Merchant | None, current_user: User
) -> None:
    """Who can manage a branch's menu: an admin, the merchant owner,
    or a manager invited to this specific branch."""
    is_admin = current_user.role in _ADMIN_ROLES
    if not (
        is_admin
        or _is_owner(merchant, current_user)
        or _is_branch_manager(db, branch, current_user)
    ):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You don't manage this branch.",
        )


@router.get("", response_model=list[BranchOut])
def list_all_branches(
    q: str | None = None,
    lat: float | None = None,
    lng: float | None = None,
    business_type: str | None = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> list[BranchOut]:
    """Marketplace-wide browse — every publicly visible (approved +
    active) branch across every merchant, unlike
    app.api.v1.endpoints.merchants.list_branches, which only ever
    shows one merchant's own branches. This is what a customer app's
    home/search screen actually calls.

    q matches the branch's own name OR any of its available menu
    items' names (case-insensitive substring) — searching "burger"
    surfaces a branch selling burgers even if it isn't named "Burger"
    anything. Pass lat & lng to sort by distance (nearest first);
    omit for unsorted. Pass business_type ("restaurant" or "grocery")
    to show just one vertical.

    Cached only for the plain-browse case (no q, no lat/lng) — that's
    a handful of keys total (one per business_type, see
    app.api.v1.endpoints.merchants._public_all_branches_key), the same
    reasoning that makes the single-merchant listing cacheable. An
    arbitrary q or a continuous lat/lng pair would turn into an
    unbounded number of cache entries for little benefit, so those
    skip the cache entirely rather than trying to bound them."""
    use_cache = not (q and q.strip()) and lat is None and lng is None
    customer_id = (
        current_user.id if current_user.role == UserRole.CUSTOMER.value else None
    )

    if use_cache:
        cached = cache_get(redis, _public_all_branches_key(business_type))
        if cached is not None:
            ids = [uuid.UUID(b["id"]) for b in cached]
            stats = get_branch_rating_stats(db, ids)
            favorited = get_favorited_branch_ids(db, customer_id, ids)
            return [_branch_out(db, b, stats, customer_id, favorited) for b in cached]

    query = (
        db.query(Branch)
        .join(Merchant, Merchant.id == Branch.merchant_id)
        .filter(
            Branch.deleted_at.is_(None),
            Branch.approval_status == BranchApprovalStatus.APPROVED.value,
            Branch.is_active.is_(True),
            Merchant.deleted_at.is_(None),
        )
    )
    if business_type is not None:
        query = query.filter(Merchant.business_type == business_type)
    if q and q.strip():
        term = f"%{q.strip()}%"
        matching_branch_ids_by_item = (
            db.query(MenuItem.branch_id)
            .join(MenuCategory, MenuCategory.id == MenuItem.category_id)
            .filter(
                MenuItem.deleted_at.is_(None),
                MenuItem.is_available.is_(True),
                MenuCategory.deleted_at.is_(None),
                MenuItem.name.ilike(term),
            )
        )
        query = query.filter(
            or_(Branch.name.ilike(term), Branch.id.in_(matching_branch_ids_by_item))
        )

    if lat is not None and lng is not None:
        distance = _distance_expr(lat, lng)
        rows = query.add_columns(distance).order_by(distance).all()
        ids = [branch.id for branch, _d in rows]
        stats = get_branch_rating_stats(db, ids)
        favorited = get_favorited_branch_ids(db, customer_id, ids)
        results = []
        for branch, distance_meters in rows:
            out = _branch_out(db, branch, stats, customer_id, favorited)
            out.distance_meters = distance_meters
            results.append(out)
        return results

    branches = query.order_by(Branch.created_at.desc()).all()
    ids = [b.id for b in branches]
    stats = get_branch_rating_stats(db, ids)
    favorited = get_favorited_branch_ids(db, customer_id, ids)
    results = [_branch_out(db, b, stats, customer_id, favorited) for b in branches]
    if use_cache:
        cache_set(
            redis,
            _public_all_branches_key(business_type),
            [r.model_dump(mode="json") for r in results],
        )
    return results


@router.get("/{branch_id}", response_model=BranchWithMenuOut)
def get_branch(
    branch_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> BranchWithMenuOut:
    """The permission check always hits the DB (it's cheap — a couple
    of indexed lookups) since it depends on who's asking; only the
    (potentially large) assembled menu payload underneath it is
    cached, keyed by branch_id, since that content is identical for
    everyone who's allowed to see it at all."""
    branch, _merchant = _get_visible_branch(db, branch_id, current_user)
    customer_id = (
        current_user.id if current_user.role == UserRole.CUSTOMER.value else None
    )

    cached = cache_get(redis, _branch_key(branch.id))
    if cached is not None:
        result = BranchWithMenuOut.model_validate(cached)
        # is_open_now is time-dependent, average_rating/review_count
        # can change independently of the menu (a new review, or an
        # admin hiding one), and is_favorited is caller-specific —
        # none of these are trusted from the cached payload, always
        # recomputed fresh, same reasoning as
        # app.api.v1.endpoints.merchants._branch_out.
        result.is_open_now = is_branch_open(branch)
        result.average_rating, result.review_count = get_branch_rating_stats(
            db, [branch.id]
        ).get(branch.id, (None, 0))
        result.is_favorited = branch.id in get_favorited_branch_ids(
            db, customer_id, [branch.id]
        )
        return result

    categories = (
        db.query(MenuCategory)
        .filter(MenuCategory.branch_id == branch.id, MenuCategory.deleted_at.is_(None))
        .order_by(MenuCategory.display_order)
        .all()
    )
    items = (
        db.query(MenuItem)
        .filter(MenuItem.branch_id == branch.id, MenuItem.deleted_at.is_(None))
        .all()
    )
    items_by_category: dict[uuid.UUID, list[MenuItem]] = {}
    for item in items:
        items_by_category.setdefault(item.category_id, []).append(item)

    groups = (
        db.query(MenuItemOptionGroup)
        .filter(
            MenuItemOptionGroup.menu_item_id.in_([i.id for i in items]),
            MenuItemOptionGroup.deleted_at.is_(None),
        )
        .order_by(MenuItemOptionGroup.display_order)
        .all()
    )
    options = (
        db.query(MenuItemOption)
        .filter(
            MenuItemOption.group_id.in_([g.id for g in groups]),
            MenuItemOption.deleted_at.is_(None),
        )
        .order_by(MenuItemOption.display_order)
        .all()
    )
    options_by_group: dict[uuid.UUID, list[MenuItemOption]] = {}
    for option in options:
        options_by_group.setdefault(option.group_id, []).append(option)
    groups_by_item: dict[uuid.UUID, list[MenuItemOptionGroup]] = {}
    for group in groups:
        groups_by_item.setdefault(group.menu_item_id, []).append(group)

    unit_by_item = {
        g.menu_item_id: g.unit_of_measure
        for g in db.query(GroceryItemDetails).filter(
            GroceryItemDetails.menu_item_id.in_([i.id for i in items])
        )
    }

    def _serialize_item(item: MenuItem) -> MenuItemWithOptionsOut:
        item_out = MenuItemOut.model_validate(item)
        item_out.unit_of_measure = unit_by_item.get(item.id)
        return MenuItemWithOptionsOut(
            **item_out.model_dump(),
            option_groups=[
                MenuItemOptionGroupWithOptionsOut(
                    **MenuItemOptionGroupOut.model_validate(group).model_dump(),
                    options=[
                        MenuItemOptionOut.model_validate(o)
                        for o in options_by_group.get(group.id, [])
                    ],
                )
                for group in groups_by_item.get(item.id, [])
            ],
        )

    result = BranchWithMenuOut(
        **_branch_out(db, branch, customer_id=customer_id).model_dump(),
        categories=[
            MenuCategoryWithItemsOut(
                **MenuCategoryOut.model_validate(category).model_dump(),
                items=[
                    _serialize_item(item)
                    for item in items_by_category.get(category.id, [])
                ],
            )
            for category in categories
        ],
    )
    cache_set(redis, _branch_key(branch.id), result.model_dump(mode="json"))
    return result


@router.patch("/{branch_id}", response_model=BranchOut)
def update_branch(
    branch_id: uuid.UUID,
    payload: BranchUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> BranchOut:
    """Partial — only fields actually sent are changed. is_active is
    the manual day-to-day open/closed switch the branch's own staff
    controls (see the Branch model docstring) — distinct from
    opens_at/closes_at (automatic/scheduled, see update_branch_hours)
    and approval_status (admin-only, see approve_branch)."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)

    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(branch, field, value)
    db.commit()
    db.refresh(branch)

    cache_delete(redis, _branch_key(branch.id))
    invalidate_public_caches(redis, branch.merchant_id)
    return _branch_out(db, branch)


@router.patch("/{branch_id}/approve", response_model=BranchOut)
def approve_branch(
    branch_id: uuid.UUID,
    payload: BranchApproveRequest,
    db: Session = Depends(get_db),
    _admin: User = Depends(require_role(UserRole.ADMIN, UserRole.SUPERADMIN)),
    redis: redis_lib.Redis = Depends(get_redis),
) -> BranchOut:
    branch, _merchant = _get_branch_and_merchant(db, branch_id)
    branch.approval_status = payload.approval_status
    db.commit()
    db.refresh(branch)

    cache_delete(redis, _branch_key(branch.id))
    invalidate_public_caches(redis, branch.merchant_id)
    return _branch_out(db, branch)


@router.patch("/{branch_id}/hours", response_model=BranchOut)
def update_branch_hours(
    branch_id: uuid.UUID,
    payload: BranchHoursUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> BranchOut:
    """Set by the branch's own staff (owner or an assigned manager),
    unlike a courier's shift (admin-only) — see the Branch model
    docstring. Partial: only fields actually sent are changed. Pass
    opens_at/closes_at as null to clear them back to "no hour
    restriction" (matches a branch that's never had hours set)."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)

    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(branch, field, value)
    db.commit()
    db.refresh(branch)

    cache_delete(redis, _branch_key(branch.id))
    invalidate_public_caches(redis, branch.merchant_id)
    return _branch_out(db, branch)


@router.patch("/{branch_id}/minimum-order", response_model=BranchOut)
def update_branch_minimum_order(
    branch_id: uuid.UUID,
    payload: BranchMinimumOrderUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> BranchOut:
    """Set by the branch's own staff, same as hours — see the Branch
    model docstring on minimum_order_amount. Pass null to clear it
    back to "no minimum"."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)

    branch.minimum_order_amount = payload.minimum_order_amount
    db.commit()
    db.refresh(branch)

    cache_delete(redis, _branch_key(branch.id))
    invalidate_public_caches(redis, branch.merchant_id)
    return _branch_out(db, branch)


def _get_menu_category_or_404(
    db: Session, branch: Branch, category_id: uuid.UUID
) -> MenuCategory:
    category = (
        db.query(MenuCategory)
        .filter(
            MenuCategory.id == category_id,
            MenuCategory.branch_id == branch.id,
            MenuCategory.deleted_at.is_(None),
        )
        .first()
    )
    if category is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Menu category not found."
        )
    return category


@router.post("/{branch_id}/categories", response_model=MenuCategoryOut)
def create_menu_category(
    branch_id: uuid.UUID,
    payload: MenuCategoryCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MenuCategoryOut:
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)

    category = MenuCategory(branch_id=branch.id, **payload.model_dump())
    db.add(category)
    db.commit()
    db.refresh(category)
    cache_delete(redis, _branch_key(branch.id))
    return MenuCategoryOut.model_validate(category)


@router.patch("/{branch_id}/categories/{category_id}", response_model=MenuCategoryOut)
def update_menu_category(
    branch_id: uuid.UUID,
    category_id: uuid.UUID,
    payload: MenuCategoryUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MenuCategoryOut:
    """Partial — only fields actually sent are changed."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    category = _get_menu_category_or_404(db, branch, category_id)

    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(category, field, value)
    db.commit()
    db.refresh(category)
    cache_delete(redis, _branch_key(branch.id))
    return MenuCategoryOut.model_validate(category)


@router.delete(
    "/{branch_id}/categories/{category_id}", status_code=status.HTTP_204_NO_CONTENT
)
def delete_menu_category(
    branch_id: uuid.UUID,
    category_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> None:
    """Refuses to delete a category that still has active items (409)
    — move or delete them first, rather than silently orphaning them
    (they'd still exist but never render in any category's menu
    listing)."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    category = _get_menu_category_or_404(db, branch, category_id)

    has_items = (
        db.query(MenuItem)
        .filter(MenuItem.category_id == category.id, MenuItem.deleted_at.is_(None))
        .first()
        is not None
    )
    if has_items:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="This category still has items — move or delete them first.",
        )

    category.deleted_at = utcnow()
    db.commit()
    cache_delete(redis, _branch_key(branch.id))


@router.post("/{branch_id}/categories/{category_id}/items", response_model=MenuItemOut)
def create_menu_item(
    branch_id: uuid.UUID,
    category_id: uuid.UUID,
    payload: MenuItemCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MenuItemOut:
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    category = _get_menu_category_or_404(db, branch, category_id)

    payload_data = payload.model_dump()
    unit_of_measure = payload_data.pop("unit_of_measure")
    payload_data["dietary_info"] = payload.dietary_info.model_dump()
    item = MenuItem(branch_id=branch.id, category_id=category.id, **payload_data)
    db.add(item)
    db.commit()
    db.refresh(item)

    if unit_of_measure is not None:
        db.add(
            GroceryItemDetails(menu_item_id=item.id, unit_of_measure=unit_of_measure)
        )
        db.commit()

    cache_delete(redis, _branch_key(branch.id))
    item_out = MenuItemOut.model_validate(item)
    item_out.unit_of_measure = unit_of_measure
    return item_out


def _get_menu_item_or_404(db: Session, branch: Branch, item_id: uuid.UUID) -> MenuItem:
    item = (
        db.query(MenuItem)
        .filter(
            MenuItem.id == item_id,
            MenuItem.branch_id == branch.id,
            MenuItem.deleted_at.is_(None),
        )
        .first()
    )
    if item is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Menu item not found."
        )
    return item


@router.patch("/{branch_id}/items/{item_id}", response_model=MenuItemOut)
def update_menu_item(
    branch_id: uuid.UUID,
    item_id: uuid.UUID,
    payload: MenuItemUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MenuItemOut:
    """Partial — only fields actually sent are changed. See
    MenuItemUpdateRequest for the unit_of_measure/category_id
    behavior."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    item = _get_menu_item_or_404(db, branch, item_id)

    updates = payload.model_dump(exclude_unset=True)
    unit_of_measure_set = "unit_of_measure" in updates
    unit_of_measure = updates.pop("unit_of_measure", None)
    dietary_info = updates.pop("dietary_info", None)
    new_category_id = updates.pop("category_id", None)

    if new_category_id is not None:
        item.category_id = _get_menu_category_or_404(db, branch, new_category_id).id

    for field, value in updates.items():
        setattr(item, field, value)
    if dietary_info is not None:
        item.dietary_info = dietary_info

    if unit_of_measure_set:
        details = (
            db.query(GroceryItemDetails)
            .filter(GroceryItemDetails.menu_item_id == item.id)
            .first()
        )
        if unit_of_measure is None:
            if details is not None:
                db.delete(details)
        elif details is not None:
            details.unit_of_measure = unit_of_measure
        else:
            db.add(
                GroceryItemDetails(
                    menu_item_id=item.id, unit_of_measure=unit_of_measure
                )
            )

    db.commit()
    db.refresh(item)
    cache_delete(redis, _branch_key(branch.id))

    details = (
        db.query(GroceryItemDetails)
        .filter(GroceryItemDetails.menu_item_id == item.id)
        .first()
    )
    item_out = MenuItemOut.model_validate(item)
    item_out.unit_of_measure = details.unit_of_measure if details else None
    return item_out


@router.delete("/{branch_id}/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_menu_item(
    branch_id: uuid.UUID,
    item_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> None:
    """Soft-delete, cascading to the item's own option groups/options
    (see MenuItemOptionGroup/MenuItemOption) — they have no meaning
    without their parent item, unlike a category, which items outlive
    independently. Past orders keep their own name/price snapshot
    regardless (see OrderItem) and are unaffected."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    item = _get_menu_item_or_404(db, branch, item_id)

    now = utcnow()
    item.deleted_at = now
    group_ids = [
        g.id
        for g in db.query(MenuItemOptionGroup.id).filter(
            MenuItemOptionGroup.menu_item_id == item.id,
            MenuItemOptionGroup.deleted_at.is_(None),
        )
    ]
    if group_ids:
        db.query(MenuItemOptionGroup).filter(
            MenuItemOptionGroup.id.in_(group_ids)
        ).update({"deleted_at": now}, synchronize_session=False)
        db.query(MenuItemOption).filter(MenuItemOption.group_id.in_(group_ids)).update(
            {"deleted_at": now}, synchronize_session=False
        )
    db.commit()
    cache_delete(redis, _branch_key(branch.id))


@router.post(
    "/{branch_id}/items/{item_id}/option-groups", response_model=MenuItemOptionGroupOut
)
def create_option_group(
    branch_id: uuid.UUID,
    item_id: uuid.UUID,
    payload: MenuItemOptionGroupCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MenuItemOptionGroupOut:
    """A branch manager/owner defines the choices customers see on this
    item (e.g. "Spice Level", "Add-ons") — the actual priced options
    within a group are added via create_option below."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    item = _get_menu_item_or_404(db, branch, item_id)

    group = MenuItemOptionGroup(menu_item_id=item.id, **payload.model_dump())
    db.add(group)
    db.commit()
    db.refresh(group)
    cache_delete(redis, _branch_key(branch.id))
    return MenuItemOptionGroupOut.model_validate(group)


def _get_option_group_or_404(
    db: Session, item: MenuItem, group_id: uuid.UUID
) -> MenuItemOptionGroup:
    group = (
        db.query(MenuItemOptionGroup)
        .filter(
            MenuItemOptionGroup.id == group_id,
            MenuItemOptionGroup.menu_item_id == item.id,
            MenuItemOptionGroup.deleted_at.is_(None),
        )
        .first()
    )
    if group is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Option group not found."
        )
    return group


@router.patch(
    "/{branch_id}/items/{item_id}/option-groups/{group_id}",
    response_model=MenuItemOptionGroupOut,
)
def update_option_group(
    branch_id: uuid.UUID,
    item_id: uuid.UUID,
    group_id: uuid.UUID,
    payload: MenuItemOptionGroupUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MenuItemOptionGroupOut:
    """Partial — only fields actually sent are changed."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    item = _get_menu_item_or_404(db, branch, item_id)
    group = _get_option_group_or_404(db, item, group_id)

    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(group, field, value)
    db.commit()
    db.refresh(group)
    cache_delete(redis, _branch_key(branch.id))
    return MenuItemOptionGroupOut.model_validate(group)


@router.delete(
    "/{branch_id}/items/{item_id}/option-groups/{group_id}",
    status_code=status.HTTP_204_NO_CONTENT,
)
def delete_option_group(
    branch_id: uuid.UUID,
    item_id: uuid.UUID,
    group_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> None:
    """Soft-delete, cascading to the group's own options — they have
    no meaning without their parent group."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    item = _get_menu_item_or_404(db, branch, item_id)
    group = _get_option_group_or_404(db, item, group_id)

    now = utcnow()
    group.deleted_at = now
    db.query(MenuItemOption).filter(
        MenuItemOption.group_id == group.id, MenuItemOption.deleted_at.is_(None)
    ).update({"deleted_at": now}, synchronize_session=False)
    db.commit()
    cache_delete(redis, _branch_key(branch.id))


@router.post(
    "/{branch_id}/items/{item_id}/option-groups/{group_id}/options",
    response_model=MenuItemOptionOut,
)
def create_option(
    branch_id: uuid.UUID,
    item_id: uuid.UUID,
    group_id: uuid.UUID,
    payload: MenuItemOptionCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MenuItemOptionOut:
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    item = _get_menu_item_or_404(db, branch, item_id)
    group = _get_option_group_or_404(db, item, group_id)

    option = MenuItemOption(group_id=group.id, **payload.model_dump())
    db.add(option)
    db.commit()
    db.refresh(option)
    cache_delete(redis, _branch_key(branch.id))
    return MenuItemOptionOut.model_validate(option)


def _get_option_or_404(
    db: Session, group: MenuItemOptionGroup, option_id: uuid.UUID
) -> MenuItemOption:
    option = (
        db.query(MenuItemOption)
        .filter(
            MenuItemOption.id == option_id,
            MenuItemOption.group_id == group.id,
            MenuItemOption.deleted_at.is_(None),
        )
        .first()
    )
    if option is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Option not found."
        )
    return option


@router.patch(
    "/{branch_id}/items/{item_id}/option-groups/{group_id}/options/{option_id}",
    response_model=MenuItemOptionOut,
)
def update_option(
    branch_id: uuid.UUID,
    item_id: uuid.UUID,
    group_id: uuid.UUID,
    option_id: uuid.UUID,
    payload: MenuItemOptionUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MenuItemOptionOut:
    """Partial — only fields actually sent are changed. Setting
    is_available=false is how an out-of-stock option (e.g. a topping)
    gets hidden without losing its history on past orders."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    item = _get_menu_item_or_404(db, branch, item_id)
    group = _get_option_group_or_404(db, item, group_id)
    option = _get_option_or_404(db, group, option_id)

    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(option, field, value)
    db.commit()
    db.refresh(option)
    cache_delete(redis, _branch_key(branch.id))
    return MenuItemOptionOut.model_validate(option)


@router.delete(
    "/{branch_id}/items/{item_id}/option-groups/{group_id}/options/{option_id}",
    status_code=status.HTTP_204_NO_CONTENT,
)
def delete_option(
    branch_id: uuid.UUID,
    item_id: uuid.UUID,
    group_id: uuid.UUID,
    option_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> None:
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    _require_branch_staff(db, branch, merchant, current_user)
    item = _get_menu_item_or_404(db, branch, item_id)
    group = _get_option_group_or_404(db, item, group_id)
    option = _get_option_or_404(db, group, option_id)

    option.deleted_at = utcnow()
    db.commit()
    cache_delete(redis, _branch_key(branch.id))


@router.post("/{branch_id}/managers", response_model=InviteResponse)
def invite_manager(
    branch_id: uuid.UUID,
    payload: PhoneAndNameRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> InviteResponse:
    """Only the merchant owner or an admin can invite a manager — a
    manager cannot invite other staff, so this deliberately doesn't
    accept a manager caller even though managers otherwise manage this
    same branch's menu (see _require_branch_staff)."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    is_admin = current_user.role in _ADMIN_ROLES
    if not (is_admin or _is_owner(merchant, current_user)):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only the merchant owner or an admin can invite managers.",
        )

    if db.query(User).filter(User.phone == payload.phone).first() is not None:
        raise _ACCOUNT_EXISTS
    if db.query(User).filter(User.email == payload.email).first() is not None:
        raise _EMAIL_EXISTS

    user = User(
        phone=payload.phone,
        name=payload.name,
        email=payload.email,
        role=UserRole.MANAGER.value,
        pin_hash=None,
    )
    db.add(user)
    db.commit()
    db.refresh(user)

    db.add(BranchManager(branch_id=branch.id, user_id=user.id))
    db.commit()

    code = otp_service.create_and_send_otp(
        db, payload.phone, OTPPurpose.ACTIVATE_ACCOUNT
    )
    response = InviteResponse(
        message="Manager invited. They'll receive an SMS code to activate their account.",
        user=UserOut.model_validate(user),
    )
    if code is not None and settings.environment == "development":
        response.debug_otp = code
    return response


@router.get("/{branch_id}/reviews", response_model=list[ReviewOut])
def list_branch_reviews(
    branch_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> list[ReviewOut]:
    """Branch staff (owner/manager) and admins see every review,
    including hidden ones (useful for moderation context); everyone
    else only sees visible ones — same is_hidden split the
    average_rating/review_count rollup on BranchOut already applies."""
    branch, merchant = _get_branch_and_merchant(db, branch_id)
    is_staff = (
        current_user.role in _ADMIN_ROLES
        or _is_owner(merchant, current_user)
        or _is_branch_manager(db, branch, current_user)
    )

    query = (
        db.query(Review, User)
        .join(User, User.id == Review.customer_id)
        .filter(Review.branch_id == branch.id)
    )
    if not is_staff:
        query = query.filter(Review.is_hidden.is_(False))

    rows = query.order_by(Review.created_at.desc()).all()
    return [
        reviews_service.to_review_out(review, customer.name)
        for review, customer in rows
    ]


@router.post("/{branch_id}/favorite", status_code=status.HTTP_204_NO_CONTENT)
def favorite_branch(
    branch_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> None:
    """Idempotent — favoriting an already-favorited branch just
    succeeds again (see app.services.favorites.add_favorite). Requires
    the branch to actually be visible (same rule as get_branch), so a
    customer can't favorite a branch id that doesn't exist or isn't
    approved/active."""
    branch, _merchant = _get_visible_branch(db, branch_id, current_user)
    favorites_service.add_favorite(db, current_user.id, branch.id)


@router.delete("/{branch_id}/favorite", status_code=status.HTTP_204_NO_CONTENT)
def unfavorite_branch(
    branch_id: uuid.UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_role(UserRole.CUSTOMER)),
) -> None:
    """No visibility check, unlike favorite_branch above — a customer
    must always be able to remove a favorite even if the branch was
    deactivated or unapproved after they favorited it. A no-op, not an
    error, if it wasn't favorited in the first place."""
    favorites_service.remove_favorite(db, current_user.id, branch_id)
