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

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

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

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

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

    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.newFileS3Keys.forEach((key) => {
        formData.append('s3_keys[]', key);
    });

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