const fs = require('fs');

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

    // Patch sendInvoiceToStore
    const search = `window.sendInvoiceToStore = async function(invId) {
  const inv = allInvoices.find(x => x.id === invId);
  if (!inv) return;`;

    const replace = `window.sendInvoiceToStore = async function(invId) {
  let inv = allInvoices.find(x => x.id === invId);
  if (!inv) {
     const dbInvs = await window.DB.getAll('transactions');
     inv = dbInvs.find(x => x.id === invId);
  }
  if (!inv) return;`;

    js = js.replace(search, replace);

    fs.writeFileSync('app_final.js', js, 'utf8');
    console.log('Patched sendInvoiceToStore');
}

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