import { recipes, userFollows, eq, or, and, inArray, sql } from "@epicure/db";

/**
 * Drizzle condition: true when `viewerId` may view a given recipe row — the
 * author, always; `public`/`unlisted` recipes, to anyone; `followers`-only
 * recipes, only to viewers who follow the author. Meant to be `and()`ed with
 * an `eq(recipes.id, id)` (or similar) in a single query, so the DB does the
 * filtering rather than fetching content the viewer can't see.
 */
export function visibleToViewer(viewerId: string) {
  return or(
    eq(recipes.authorId, viewerId),
    inArray(recipes.visibility, ["public", "unlisted"]),
    and(
      eq(recipes.visibility, "followers"),
      sql`exists (select 1 from ${userFollows} where ${userFollows.followerId} = ${viewerId} and ${userFollows.followingId} = ${recipes.authorId})`
    )
  );
}
