import axios from "axios";
import {toast} from "react-hot-toast";

export function downloadBatchBarcode(batchId: number) {
    try {
        axios
            .post('/api/pda/batchBarcodePrint', {id: batchId})
            .then((response) => {
                const dataUri = response.data.data
                if (!dataUri) {
                    console.error('No image data found in JSON response')
                    return
                }

                // Create a temporary <a> element and trigger download
                const link = document.createElement('a')
                link.href = dataUri
                link.download = `barcode_${batchId}.png`
                // Append to DOM, click it, then remove it
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
            })
            .catch((error) => {
                console.error(error)
                toast.error('Failed to fetch or download barcode')
            })
    }
    catch (e) {
        console.error(e)
        toast.error('Failed to fetch or download barcode')
    }
}
