// lib/process/aggregate-case-artifacts.js — collect the artifact IDs for a
// case, in display order, with the intake form artifact first.
//
// The case-level intake form artifact is created at startCase (before any
// execution row exists) and lives on `case.context.intake_form_artifact_id`.
// Stage executions append further artifact IDs via `execution.artifact_ids`.
// This helper merges both sources while deduping and preserving insertion
// order so the intake form always sorts to the front.

export function aggregateCaseArtifacts(caseRow, executions) {
  const intakeFormId = caseRow?.context?.intake_form_artifact_id || null;
  const seen = new Set();
  const ids = [];
  if (intakeFormId) {
    ids.push(intakeFormId);
    seen.add(intakeFormId);
  }
  for (const e of executions || []) {
    for (const id of e?.artifact_ids || []) {
      if (id && !seen.has(id)) {
        ids.push(id);
        seen.add(id);
      }
    }
  }
  return ids;
}
