/**
 * Dropping an already-stored image from a picker that also holds new uploads.
 *
 * Four forms — event, community post, reply and reply-of-reply — each carried a
 * byte-identical copy of this handler, and each copy typed its `setFieldValue`
 * parameter as `(field: string, value: any) => void` and its file predicate as
 * `(file: any) => file instanceof File`. One copy, two honest types.
 *
 * The three pieces of state it keeps in step:
 *
 *  - the preview list the picker renders (`images`);
 *  - `existing_image_ids[]`, the keep-set the backend diffs against — an id
 *    removed from here is the only way to tell the API to delete that image;
 *  - the Formik field, which must be reduced to *new* `File` objects only.
 *    Stored images are plain `{ id, image }` records that share the field with
 *    freshly-picked `File`s, and sending one back as if it were an upload is
 *    what the `instanceof File` filter prevents.
 */

import type { FormikValues } from "formik";
import type { SetFieldValueFn } from "@/components/ui/useUploadDocument";

/** A stored image as the pickers hold it. */
export interface StoredImage {
  id: number;
  image: string;
}

export type RemoveExistingImage = (
  index: number,
  isExistingFile: boolean,
  fieldName: string,
  setFieldValue: SetFieldValueFn,
  values: FormikValues
) => void;

export function makeRemoveExistingImage({
  images,
  setImages,
  setExistingImageIds,
}: {
  images: StoredImage[];
  setImages: (update: (prev: StoredImage[]) => StoredImage[]) => void;
  setExistingImageIds: (update: (prev: number[]) => number[]) => void;
}): RemoveExistingImage {
  return (index, isExistingFile, fieldName, setFieldValue, values) => {
    /* Only a stored image needs this bookkeeping; the picker removes a
       not-yet-uploaded File from the Formik array by itself. */
    if (!isExistingFile) return;

    const removedImageId = images[index]?.id;
    if (removedImageId === undefined) return;

    setImages((prev) => prev.filter((_, i) => i !== index));
    setExistingImageIds((prev) => prev.filter((id) => id !== removedImageId));

    const currentFiles = Array.isArray(values[fieldName])
      ? (values[fieldName] as unknown[])
      : [];
    setFieldValue(
      fieldName,
      currentFiles.filter((file) => file instanceof File)
    );
  };
}
