export type MediaItem = {
    id: number;
    url: string;
    thumb_url: string;
};

export type MediaUploadState = {
    existing: MediaItem[];
    newFiles: File[];
    removeIds: number[];
};

export function createMediaUploadState(existing: MediaItem[] = []): MediaUploadState {
    return {
        existing: [...existing],
        newFiles: [],
        removeIds: [],
    };
}

export function mediaCount(state: MediaUploadState): number {
    return state.existing.length + state.newFiles.length;
}

export function appendMediaToFormData(
    formData: FormData,
    prefix: string,
    state: MediaUploadState,
): void {
    state.newFiles.forEach((file) => {
        formData.append(`${prefix}[images][]`, file);
    });

    state.removeIds.forEach((id) => {
        formData.append(`${prefix}[remove_media_ids][]`, String(id));
    });
}

export function appendPhotosToFormData(
    formData: FormData,
    photos: File[],
    removeMediaIds: number[] = [],
): void {
    photos.forEach((file) => {
        formData.append('photos[]', file);
    });

    removeMediaIds.forEach((id) => {
        formData.append('remove_media_ids[]', String(id));
    });
}

export function appendRootPhotosToFormData(formData: FormData, state: MediaUploadState): void {
    state.newFiles.forEach((file) => {
        formData.append('photos[]', file);
    });

    state.removeIds.forEach((id) => {
        formData.append('remove_media_ids[]', String(id));
    });
}
