const { JsonRpcProvider, formatEther } = require('ethers');
const { EVM_CANDIDATE_CONFIG } = require('../config/evmCandidateConfig');
const operatorCustodyService = require('./operatorCustodyService');

const OWNER_LOGIN_ID = 'superadmin';

async function getOperatorWalletSummary() {
  const address = operatorCustodyService.getConfiguredOperatorAddress();
  const custody = operatorCustodyService.getStatus();
  if (!address) {
    return {
      configured: false,
      ownerLoginId: OWNER_LOGIN_ID,
      signerOnline: false,
      signingEnabled: false,
      error: 'OPERATOR_ADDRESS_NOT_CONFIGURED'
    };
  }

  const provider = new JsonRpcProvider(EVM_CANDIDATE_CONFIG.rpcUrl, undefined, { staticNetwork: false });
  try {
    const [network, balance, blockNumber] = await Promise.all([
      provider.getNetwork(),
      provider.getBalance(address),
      provider.getBlockNumber()
    ]);
    const chainId = Number(network.chainId);
    return {
      configured: true,
      online: chainId === EVM_CANDIDATE_CONFIG.chainId,
      ownerLoginId: OWNER_LOGIN_ID,
      address,
      balanceWei: balance.toString(),
      balance: formatEther(balance),
      chainId,
      blockNumber,
      custody: custody.mode || 'offline-dpapi',
      custodyReady: custody.ok,
      signerOnline: false,
      signingEnabled: false,
      externalTransfersEnabled: EVM_CANDIDATE_CONFIG.externalTransfersEnabled,
      error: chainId === EVM_CANDIDATE_CONFIG.chainId ? '' : 'CHAIN_ID_MISMATCH'
    };
  } catch (error) {
    return {
      configured: true,
      online: false,
      ownerLoginId: OWNER_LOGIN_ID,
      address,
      balanceWei: '',
      balance: '',
      chainId: EVM_CANDIDATE_CONFIG.chainId,
      blockNumber: null,
      custody: custody.mode || 'offline-dpapi',
      custodyReady: custody.ok,
      signerOnline: false,
      signingEnabled: false,
      externalTransfersEnabled: EVM_CANDIDATE_CONFIG.externalTransfersEnabled,
      error: error.code || 'RPC_UNAVAILABLE'
    };
  }
}

async function sendOperatorTransfer({ to, amount, memo } = {}) {
  void to;
  void amount;
  void memo;
  throw operatorCustodyService.signerOfflineError();
}

module.exports = { getOperatorWalletSummary, sendOperatorTransfer, OWNER_LOGIN_ID };
