const fs = require('fs');

if (fs.existsSync('app_final.js')) {
    let js = fs.readFileSync('app_final.js', 'utf8');

    js = js.replace(
        "if (entityType === 'item') return allInvoices.some(inv => inv.items.some(it => it.item_id === id));",
        "if (entityType === 'item') return allInvoices.some(inv => inv.items && inv.items.some(it => String(it.item_id) === String(id)));"
    );

    // Also we should ensure string matching because id might be passed as string from HTML
    // and item_id might be stored as integer or vice versa.

    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Patched isEntityReferenced successfully!');
}

// Cache buster
let html = fs.readFileSync('index.html', 'utf8');
html = html.replace(/v=\d+/g, 'v=' + Date.now());
fs.writeFileSync('index.html', html, 'utf8');
