import { db, ratings, inArray, sql } from "@epicure/db";

export type RatingSummary = { avgRating: number; ratingCount: number };

/** Average score + review count per recipe, for a batch of recipe ids — used to show rating stars on list/search cards without a per-row join. */
export async function getAvgRatingsByRecipeId(recipeIds: string[]): Promise<Map<string, RatingSummary>> {
  if (recipeIds.length === 0) return new Map();

  const rows = await db
    .select({
      recipeId: ratings.recipeId,
      avgScore: sql<number>`avg(${ratings.score})::float`,
      count: sql<number>`count(*)::int`,
    })
    .from(ratings)
    .where(inArray(ratings.recipeId, recipeIds))
    .groupBy(ratings.recipeId);

  return new Map(rows.map((r) => [r.recipeId, { avgRating: r.avgScore, ratingCount: r.count }]));
}
