#!/usr/bin/env node
/**
 * Quick Bank Account Update Script
 * Updates bank accounts in BankTransferService.js
 */

const fs = require('fs');
const path = require('path');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const bankAccounts = [];

console.log('\n🏦 WakaTraffic Bank Account Setup\n');
console.log('Enter your business bank account details for deposits.\n');
console.log('You can add 1-5 bank accounts. Press Enter to skip optional accounts.\n');

function question(prompt) {
  return new Promise((resolve) => {
    rl.question(prompt, resolve);
  });
}

async function getBankAccount(index) {
  console.log(`\n--- Account ${index} ${index === 1 ? '(Required)' : '(Optional)'} ---`);

  const bankName = await question('Bank Name (e.g., Access Bank): ');
  if (!bankName && index > 1) return null;

  const accountNumber = await question('Account Number: ');
  const accountName = await question('Account Name: ');
  const bankCode = await question('Bank Code (e.g., 044 for Access): ');

  return {
    bank_name: bankName,
    account_number: accountNumber,
    account_name: accountName,
    bank_code: bankCode
  };
}

async function main() {
  // Get first account (required)
  const account1 = await getBankAccount(1);
  if (account1) bankAccounts.push(account1);

  // Get optional accounts
  for (let i = 2; i <= 3; i++) {
    const addMore = await question(`\nAdd another bank account? (y/n): `);
    if (addMore.toLowerCase() !== 'y') break;

    const account = await getBankAccount(i);
    if (account) bankAccounts.push(account);
  }

  if (bankAccounts.length === 0) {
    console.log('\n❌ No bank accounts provided. Exiting...\n');
    rl.close();
    return;
  }

  // Generate the accounts array code
  const accountsCode = bankAccounts.map(acc => `      {
        bank_name: '${acc.bank_name}',
        account_number: '${acc.account_number}',
        account_name: '${acc.account_name}',
        bank_code: '${acc.bank_code}'
      }`).join(',\n');

  console.log('\n✅ Bank accounts configured:\n');
  bankAccounts.forEach((acc, i) => {
    console.log(`${i + 1}. ${acc.bank_name} - ${acc.account_number} (${acc.account_name})`);
  });

  const confirm = await question('\nUpdate BankTransferService.js with these accounts? (y/n): ');

  if (confirm.toLowerCase() !== 'y') {
    console.log('\n❌ Cancelled. No changes made.\n');
    rl.close();
    return;
  }

  // Read the service file
  const servicePath = path.join(__dirname, '../services/payments/BankTransferService.js');
  let serviceCode = fs.readFileSync(servicePath, 'utf8');

  // Replace the bankAccounts array
  const pattern = /this\.bankAccounts = \[[\s\S]*?\];/;
  const replacement = `this.bankAccounts = [
${accountsCode}
    ];`;

  serviceCode = serviceCode.replace(pattern, replacement);

  // Write back
  fs.writeFileSync(servicePath, serviceCode, 'utf8');

  console.log('\n✅ Bank accounts updated successfully!\n');
  console.log('📝 File updated: /services/payments/BankTransferService.js\n');
  console.log('🔄 Next steps:');
  console.log('   1. Restart your server: npm run dev');
  console.log('   2. Test deposit: http://localhost:5000/deposit.html');
  console.log('   3. Select "Bank Transfer" and verify your accounts appear\n');

  rl.close();
}

main().catch(error => {
  console.error('Error:', error);
  rl.close();
  process.exit(1);
});
