/* eslint-disable no-restricted-globals */
self.onmessage = async function (e) {
	const { action, files } = e.data;

	let processFiles = 0;

	if (action === "processImages") {
		for (const file of files) {
			try {
				const formData = new FormData();
				formData.append("image", file, file.name);

				const response = await fetch(`${process.env.REACT_APP_API_URL}/detect_image`, {
					method: "POST",
					body: formData,
				});

				const result = await response.json();
				self.postMessage({ status: "success", result, total: files.length, processFiles: ++processFiles });
			} catch (error) {
				self.postMessage({ status: "error", error: error.message });
			}
		}
	}
};
