import type { Attachment } from "@root/model/attachment"

type KeyValue<T = string> = {
  [key: string]: T;
};

const convertBinaryStringToFile = ({
	name,
	content,
	mimetype,
}: Attachment): File => {
	const bytes = new Uint8Array(content.length)

	for (let index = 0; index < content.length; index += 1) {
		bytes[index] = content.charCodeAt(index)
	}

	const blob = new Blob([bytes], { type: mimetype })

	return new File([blob], name, { type: blob.type })
}

export const jsonToFormdata = (
	json: KeyValue<string | Attachment>
): FormData => {
	const formData = new FormData()

	for (const key in json) {
		if (!key) continue

		const value = json[key]

		if (typeof value !== "string") {
			formData.append(key, convertBinaryStringToFile(value))

			continue
		}

		formData.append(key, value)
	}

	return formData
}
