'use strict';
const { ethers } = require('ethers');
const provider = new ethers.JsonRpcProvider(process.env.CELO_RPC_URL || 'https://forno.celo.org');

const BLOCKED_CONTRACTS = [
  '0x765DE816845861e75A25fCA122bb6898B8B1282a',
  '0xcebA9300f2b948710d2653dD7B07f33A8B32118C',
  '0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e',
  '0x471EcE3750Da237f93B8E339c536989b8978a438',
  '0xD8763CBa276a3738E6DE85b4b3bF5FDed6D6cA73',
  '0xe8537a3d056DA446677B9E9d6c5dB704EaAb4787',
  '0xE3D8bd6Aed4F159bc8000a9cD47CffDb95F96121',
  '0x1421bDe4B10e8dd459b3BCb598810B1337D56842',
  '0x0000000000000000000000000000000000000000',
].map(a => a.toLowerCase());

async function isContractAddress(address) {
  try {
    const code = await provider.getCode(address);
    return code !== '0x' && code !== '0x0';
  } catch (e) {
    console.error('[WalletValidation] getCode failed:', e.message);
    return false;
  }
}

async function validateWalletAddress(address) {
  if (!address || !/^0x[a-fA-F0-9]{40}$/.test(address)) {
    return { valid: false, error: '❌ Invalid wallet address. Must start with 0x followed by 40 hex characters.', code: 'INVALID_FORMAT' };
  }
  if (BLOCKED_CONTRACTS.includes(address.toLowerCase())) {
    return { valid: false, error: '❌ <b>That is a token contract address, not a personal wallet!</b>\n\nYou copied a contract address instead of your wallet address.\n\n<b>How to find YOUR address:</b>\n1. Open MetaMask / Valora / MiniPay\n2. Tap your address at the top\n3. Paste it here\n\n<i>⚠️ Sending crypto to a contract = permanent loss!</i>', code: 'KNOWN_CONTRACT' };
  }
  try {
    if (await isContractAddress(address)) {
      return { valid: false, error: '❌ <b>That address is a smart contract, not a personal wallet!</b>\n\nPlease enter your personal wallet address from MetaMask, Valora, or MiniPay.', code: 'DETECTED_CONTRACT' };
    }
  } catch (e) {
    console.warn('[WalletValidation] On-chain check failed:', e.message);
  }
  return { valid: true };
}

module.exports = { BLOCKED_CONTRACTS, isContractAddress, validateWalletAddress };
