| 1 | import type { MemorySelection, WorkplaceData } from "@/lib/types"; |
| 2 | |
| 3 | function selectionKey(selection: MemorySelection): string { |
| 4 | return `${selection.memory_id}|${selection.source_shot_id}|${selection.frame_index}`; |
| 5 | } |
| 6 | |
| 7 | /** |
| 8 | * Collect every confirmed Memory selection across approved shot reviews. |
| 9 | * Falls back to the canonical `memory_bank` snapshot when no approved reviews exist. |
| 10 | */ |
| 11 | export function collectConfirmedMemoryEntries( |
| 12 | workplace: WorkplaceData | null | undefined, |
| 13 | ): MemorySelection[] { |
| 14 | if (!workplace) return []; |
| 15 | |
| 16 | const seen = new Set<string>(); |
| 17 | const collected: MemorySelection[] = []; |
| 18 | |
| 19 | for (const shot of workplace.shots ?? []) { |
| 20 | const review = shot.memory_review; |
| 21 | if (!review || review.status !== "approved") continue; |
| 22 | |
| 23 | for (const selection of review.selections ?? []) { |
| 24 | if (!selection?.image?.url) continue; |
| 25 | const key = selectionKey(selection); |
| 26 | if (seen.has(key)) continue; |
| 27 | seen.add(key); |
| 28 | collected.push(selection); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | if (collected.length === 0) { |
| 33 | return (workplace.memory_bank ?? []).filter((entry) => |
| 34 | Boolean(entry?.image?.url), |
| 35 | ); |
| 36 | } |
| 37 | |
| 38 | collected.sort((a, b) => { |
| 39 | if (a.source_shot_id !== b.source_shot_id) { |
| 40 | return a.source_shot_id - b.source_shot_id; |
| 41 | } |
| 42 | return a.memory_id.localeCompare(b.memory_id); |
| 43 | }); |
| 44 | |
| 45 | return collected; |
| 46 | } |
| 47 |