import uuid

from sqlalchemy import func
from sqlalchemy.orm import Session

from app.models.review import Review
from app.schemas.review import ReviewOut


def to_review_out(review: Review, customer_name: str) -> ReviewOut:
    """Shared by every endpoint that returns a review — create
    (app.api.v1.endpoints.orders), update/reply/visibility, and the
    branch listing (app.api.v1.endpoints.branches) — since
    customer_name isn't a Review column (see the ReviewOut docstring),
    it always has to be attached the same way."""
    out = ReviewOut.model_validate(review)
    out.customer_name = customer_name
    return out


def get_branch_rating_stats(
    db: Session, branch_ids: list[uuid.UUID]
) -> dict[uuid.UUID, tuple[float | None, int]]:
    """(average_rating, review_count) per branch_id, visible reviews
    only (is_hidden excluded) — a single grouped query for however
    many branches are being rendered at once, so a listing of many
    branches (see app.api.v1.endpoints.merchants.list_branches)
    doesn't do one query per branch. A branch with no visible reviews
    at all simply isn't a key in the returned dict — callers default
    it to (None, 0)."""
    if not branch_ids:
        return {}
    rows = (
        db.query(Review.branch_id, func.avg(Review.rating), func.count(Review.id))
        .filter(Review.branch_id.in_(branch_ids), Review.is_hidden.is_(False))
        .group_by(Review.branch_id)
        .all()
    )
    return {
        branch_id: (float(avg_rating), count) for branch_id, avg_rating, count in rows
    }
