import uuid

from sqlalchemy.orm import Session

from app.models.branch import Branch
from app.models.favorite import Favorite


def add_favorite(db: Session, customer_id: uuid.UUID, branch_id: uuid.UUID) -> None:
    """Idempotent — favoriting an already-favorited branch again is a
    no-op, not a conflict, same as the DeviceToken registration
    pattern in app.services.push."""
    exists = (
        db.query(Favorite)
        .filter(Favorite.customer_id == customer_id, Favorite.branch_id == branch_id)
        .first()
    )
    if exists is not None:
        return
    db.add(Favorite(customer_id=customer_id, branch_id=branch_id))
    db.commit()


def remove_favorite(db: Session, customer_id: uuid.UUID, branch_id: uuid.UUID) -> None:
    db.query(Favorite).filter(
        Favorite.customer_id == customer_id, Favorite.branch_id == branch_id
    ).delete()
    db.commit()


def get_favorited_branch_ids(
    db: Session, customer_id: uuid.UUID | None, branch_ids: list[uuid.UUID]
) -> set[uuid.UUID]:
    """Bulk-fetch, same shape as
    app.services.reviews.get_branch_rating_stats — one query for a
    whole list of branches rather than one per branch. customer_id is
    optional so callers can pass current_user.id unconditionally
    without special-casing non-customer roles (staff/admin/courier
    simply never have any favorites, so this returns empty for them)."""
    if customer_id is None or not branch_ids:
        return set()
    rows = (
        db.query(Favorite.branch_id)
        .filter(Favorite.customer_id == customer_id, Favorite.branch_id.in_(branch_ids))
        .all()
    )
    return {branch_id for (branch_id,) in rows}


def list_favorite_branches(db: Session, customer_id: uuid.UUID) -> list[Branch]:
    return (
        db.query(Branch)
        .join(Favorite, Favorite.branch_id == Branch.id)
        .filter(Favorite.customer_id == customer_id, Branch.deleted_at.is_(None))
        .order_by(Favorite.created_at.desc())
        .all()
    )
