require('../config/loadEnv')();
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const walletService = require('../services/evmWalletService');

async function main() {
  const ownerId = `self-test-${Date.now()}`;
  const pin = '73918426';
  const result = walletService.createWalletForOwner({ ownerId, pin, label: 'Self Test Wallet' });
  assert.equal(result.created, true);
  assert.equal(walletService.validateAddress(result.wallet.address), true);
  assert.equal(result.wallet.address, result.recovery.address);

  const restored = walletService.exportRecoveryForOwner({ ownerId, pin });
  assert.equal(restored.privateKey, result.recovery.privateKey);

  const signed = await walletService.signMessageForOwner({ ownerId, pin, message: 'PLAIS EVM self test' });
  assert.equal(signed.verified, true);

  let rejected = false;
  try {
    walletService.exportRecoveryForOwner({ ownerId, pin: '111111' });
  } catch (error) {
    rejected = error.code === 'INVALID_EVM_PIN';
  }
  assert.equal(rejected, true);

  const storePath = path.join(__dirname, '..', 'data', 'evm-wallets.json');
  const store = JSON.parse(fs.readFileSync(storePath, 'utf8'));
  store.wallets = store.wallets.filter(wallet => wallet.ownerId !== ownerId);
  fs.writeFileSync(storePath, `${JSON.stringify(store, null, 2)}\n`);
  console.log(JSON.stringify({ ok: true, address: result.wallet.address, signatureVerified: signed.verified }));
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
