import { Injectable, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

const ALLOWED_METHODS = [
  'eth_blockNumber', 'eth_getBlockByNumber', 'eth_getBlockByHash',
  'eth_getTransactionByHash', 'eth_getTransactionReceipt', 'eth_call',
  'eth_estimateGas', 'eth_sendRawTransaction', 'eth_getBalance',
  'eth_getCode', 'eth_getLogs', 'eth_chainId', 'net_version',
];

@Injectable()
export class RpcService {
  private rpcUrl: string;

  constructor(private config: ConfigService) {
    this.rpcUrl = this.config.get('rpcUrl')!;
  }

  async proxy(request: { jsonrpc: string; method: string; params: any[]; id: number }) {
    if (!ALLOWED_METHODS.includes(request.method)) {
      throw new BadRequestException(`Method ${request.method} not allowed`);
    }

    const response = await fetch(this.rpcUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        jsonrpc: '2.0',
        method: request.method,
        params: request.params || [],
        id: request.id || 1,
      }),
    });

    return response.json();
  }
}
