import CustomError from './error';

export function parseChainError(err: unknown): CustomError {
  const msg = (err as Error)?.message ?? String(err);

  const gasMatch = msg.match(
    /Insufficient fund to pay for tx cost from (\w+)[\s\S]*?expected\s+([\d.]+)\s+(\w+)[\s\S]*?got\s+([\d.]+)/
  );
  if (gasMatch) {
    return new CustomError('INSUFFICIENT_GAS', 'Main account lacks gas token for tx cost').withDetails({
      account: gasMatch[1],
      required: gasMatch[2],
      available: gasMatch[4],
      token: gasMatch[3],
    });
  }

  // Chain rejects gas-payer JWT when the signing account has no on-chain state
  // (fresh DID that never broadcast a DeclareTx). The wallet shouldn't attach
  // x-gas-payer-* headers in that case, but surface a clean code/message so the
  // UI doesn't render the raw GraphQL string. See #1356.
  const gasPayerNotOnChain = msg.match(/Gas payer (\w+)[\s\S]*?does not exist on chain/i);
  if (gasPayerNotOnChain) {
    return new CustomError(
      'GAS_PAYER_NOT_ON_CHAIN',
      'Wallet account has no on-chain history yet; please fund or transact once before paying'
    ).withDetails({ account: gasPayerNotOnChain[1] });
  }

  return new CustomError('TX_REJECTED', msg).withDetails({ raw: msg });
}
