import type { ConditionCatalogueRow } from '../../../services/CampaignService'; /** * The catalogue rows a segment's codes select, or null when those codes are not whole rows. A * partial row or an unlisted code cannot be shown as a choice, so editing it here would change the * audience without anyone choosing that. */ export function selectedConditionRows(codes: readonly string[], rows: readonly ConditionCatalogueRow[]): ConditionCatalogueRow[] | null { const chosen = rows.filter((row) => row.codes.some((code) => codes.includes(code))); if (chosen.some((row) => !row.codes.every((code) => codes.includes(code)))) return null; const covered = new Set(chosen.flatMap((row) => row.codes)); if (codes.some((code) => !covered.has(code))) return null; return chosen; } /** The codes after choosing or clearing one row, in catalogue order so the same choice is the same segment. */ export function toggleConditionRow(codes: readonly string[], rows: readonly ConditionCatalogueRow[], rowId: string, selected: boolean): string[] { const ids = new Set((selectedConditionRows(codes, rows) ?? []).map((row) => row.id)); if (selected) ids.add(rowId); else ids.delete(rowId); return rows.filter((row) => ids.has(row.id)).flatMap((row) => row.codes); }