const fs = require('fs');

try {
    let js = fs.readFileSync('vouchers_returns.js', 'utf8');

    // Fix sales-returns-treasury null error
    js = js.replace(/const treasurySelect = document\.getElementById\('sales-returns-treasury'\);\s+const cashAccounts = currentAccounts\.filter\([\s\S]*?\);\s+treasurySelect\.innerHTML = '<option value="">-- [^<]+ --<\/option>';\s+cashAccounts\.forEach\(a => \{\s+treasurySelect\.innerHTML \+= `<option value="\$\{a\.id\}">\$\{a\.name\}<\/option>`;\s+\}\);/, (match) => {
        return `const treasurySelect = document.getElementById('sales-returns-treasury');\n    if (treasurySelect) {\n${match.replace("const treasurySelect = document.getElementById('sales-returns-treasury');\n", "").replace("const treasurySelect = document.getElementById('sales-returns-treasury');", "")}\n    }`;
    });

    // Fix purchases-returns-treasury null error
    js = js.replace(/const pTreasurySelect = document\.getElementById\('purchases-returns-treasury'\);\s+const pCashAccounts = currentAccounts\.filter\([\s\S]*?\);\s+pTreasurySelect\.innerHTML = '<option value="">-- [^<]+ --<\/option>';\s+pCashAccounts\.forEach\(a => \{\s+pTreasurySelect\.innerHTML \+= `<option value="\$\{a\.id\}">\$\{a\.name\}<\/option>`;\s+\}\);/, (match) => {
        return `const pTreasurySelect = document.getElementById('purchases-returns-treasury');\n    if (pTreasurySelect) {\n${match.replace("const pTreasurySelect = document.getElementById('purchases-returns-treasury');\n", "").replace("const pTreasurySelect = document.getElementById('purchases-returns-treasury');", "")}\n    }`;
    });

    fs.writeFileSync('vouchers_returns.js', js, 'utf8');

    // Bust cache for vouchers_returns.js
    let html = fs.readFileSync('index.html', 'utf8');
    html = html.replace(/vouchers_returns\.js\?v=\d+/g, 'vouchers_returns.js?v=' + Date.now());
    fs.writeFileSync('index.html', html, 'utf8');
    
    console.log("Patched vouchers_returns.js treasury nulls.");
} catch(e) {
    console.error(e);
}
