const fs = require('fs');

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

    // 1. Fix editSalesReturn treasurySelect
    js = js.replace(/const treasurySelect = document\.getElementById\('sales-returns-treasury'\);\s*treasurySelect\.innerHTML = '[^']*';\s*currentAccounts\.filter[\s\S]*?\}\);/g, (match) => {
        return `const treasurySelect = document.getElementById('sales-returns-treasury');\n    if (treasurySelect) {\n        ${match.replace(/const treasurySelect = document\.getElementById\('sales-returns-treasury'\);\s*/, '')}\n    }`;
    });

    // 2. Fix editPurchasesReturn pTreasurySelect
    js = js.replace(/const pTreasurySelect = document\.getElementById\('purchases-returns-treasury'\);\s*pTreasurySelect\.innerHTML = '[^']*';\s*currentAccounts\.filter[\s\S]*?\}\);/g, (match) => {
        return `const pTreasurySelect = document.getElementById('purchases-returns-treasury');\n    if (pTreasurySelect) {\n        ${match.replace(/const pTreasurySelect = document\.getElementById\('purchases-returns-treasury'\);\s*/, '')}\n    }`;
    });

    // 3. Fix save sales returns value
    js = js.replace(/document\.getElementById\('sales-returns-treasury'\)\.value/g, "document.getElementById('sales-returns-treasury')?.value");

    // 4. Fix save purchases returns value
    js = js.replace(/document\.getElementById\('purchases-returns-treasury'\)\.value/g, "document.getElementById('purchases-returns-treasury')?.value");

    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 completely.");
} catch(e) {
    console.error(e);
}
