import { prisma } from "./prisma";

/**
 * Return the subset of `exerciseIds` that do NOT belong to `userId`.
 *
 * Exercises are per-user (`Exercise.userId`, `@@unique([userId, name])`) —
 * even curated-library entries are copied per account. Routes that write
 * SetLogs from a client-supplied exerciseId must check ownership first;
 * otherwise a user could attach another user's exercise to their own
 * workout, which leaks that exercise's name/notes back on fetch and wires
 * up a cross-user `onDelete: Cascade` dependency.
 *
 * Unknown ids and ids owned by someone else are deliberately
 * indistinguishable in the result, so a caller's 400 can't be used to
 * probe which exerciseIds exist. An empty input returns an empty array
 * (no query).
 */
export async function findUnownedExerciseIds(
  userId: string,
  exerciseIds: Iterable<string>,
): Promise<string[]> {
  const ids = Array.from(new Set(exerciseIds));
  if (ids.length === 0) return [];

  const owned = await prisma.exercise.findMany({
    where: { userId, id: { in: ids } },
    select: { id: true },
  });
  const ownedIds = new Set(owned.map((e) => e.id));

  return ids.filter((id) => !ownedIds.has(id));
}
