/**
 * Telling the API which already-stored images to keep.
 *
 * The backend diffs a keep-set: `App\Support\MediaKeepSet::validate()` reads
 * `existing_image_ids`, and `::apply()` soft-deletes every image of the record
 * that is **not** in it. The rule that matters, and that six call sites got
 * wrong in the same way, is what happens when the set is *empty*:
 *
 *  - the key **absent** means "keep everything" (`validate()` returns `null`
 *    and `apply()` does nothing);
 *  - `existing_image_ids[]` appended zero times **is** absent — multipart has
 *    no representation for an empty array;
 *  - so a form that writes the ids inside `if (ids.length > 0)` cannot ever
 *    say "keep none", and removing the last image silently kept them all.
 *
 * `MediaKeepSet::normalizeEmptySignal()` exists for exactly this: a *scalar*
 * `existing_image_ids` of `""` or `"none"` is rewritten to `[]` before
 * validation. The three publish forms already used that sentinel, but only on
 * their republish branch — their edit branch had the hole, as did all three
 * community forms.
 *
 * Call this on an **update** only. `store()` does not read the key, and the
 * opportunity and event controllers use `RejectsUnknownWriteKeys`, which 422s
 * the whole request on a key their validator does not list.
 */

/** The scalar the backend rewrites to an empty keep-set. */
export const IMAGE_KEEP_SET_NONE = "none";

export function appendImageKeepSet(
  formData: FormData,
  keepIds: readonly number[]
): void {
  if (keepIds.length === 0) {
    formData.append("existing_image_ids", IMAGE_KEEP_SET_NONE);
    return;
  }
  for (const id of keepIds) {
    formData.append("existing_image_ids[]", String(id));
  }
}
