import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Redis from 'ioredis';

@Injectable()
export class AccountingService {
  private readonly logger = new Logger(AccountingService.name);
  private redis: Redis;

  constructor(private config: ConfigService) {
    this.redis = new Redis(this.config.get('REDIS_URL') || 'redis://localhost:6379/2');
  }

  /** 记录 Gas 消耗 */
  async recordGasSpent(userAddress: string, gasUsed: string): Promise<void> {
    const gasAmount = BigInt(gasUsed);

    // 记录用户级 Gas 消耗
    await this.redis.hincrby('gas:per_user', userAddress, Number(gasAmount));

    // 记录全局 Gas 消耗
    await this.redis.incrby('gas:total', Number(gasAmount));

    // 记录交易计数
    await this.redis.incr('gas:tx_count');

    this.logger.debug(`Gas recorded: ${userAddress} used ${gasUsed}`);
  }

  /** 获取 Gas 补贴统计 */
  async getStats() {
    const [totalGas, txCount, perUser] = await Promise.all([
      this.redis.get('gas:total'),
      this.redis.get('gas:tx_count'),
      this.redis.hgetall('gas:per_user'),
    ]);

    return {
      totalGasSpent: totalGas || '0',
      totalTransactions: parseInt(txCount || '0', 10),
      topUsers: Object.entries(perUser)
        .map(([address, gas]) => ({ address, gasSpent: gas }))
        .sort((a, b) => parseInt(b.gasSpent) - parseInt(a.gasSpent))
        .slice(0, 20),
    };
  }
}
