import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { PlantingEventConsumerService, PlantingCreatedPayload } from '@/infrastructure/kafka';
import { WalletApplicationService } from '@/application/services';

/**
 * 处理认种创建事件
 *
 * 当用户认种一棵树后：
 * 1. 标记用户为已认种（后续分享权益直接进入可结算）
 * 2. 结算该用户所有待领取奖励（从 PENDING 变为 SETTLED）
 */
@Injectable()
export class PlantingCreatedHandler implements OnModuleInit {
  private readonly logger = new Logger(PlantingCreatedHandler.name);

  constructor(
    private readonly plantingEventConsumer: PlantingEventConsumerService,
    private readonly walletService: WalletApplicationService,
  ) {}

  onModuleInit() {
    this.plantingEventConsumer.onPlantingCreated(this.handlePlantingCreated.bind(this));
    this.logger.log('PlantingCreatedHandler registered');
  }

  private async handlePlantingCreated(payload: PlantingCreatedPayload): Promise<void> {
    const { orderNo, accountSequence, userId, treeCount } = payload;

    this.logger.log(`[PLANTING] User ${accountSequence} planted ${treeCount} tree(s), order: ${orderNo}`);

    try {
      // 1. 标记用户为已认种（后续分享权益直接进入可结算）
      await this.walletService.markUserAsPlanted(accountSequence);

      // 2. 结算用户所有待领取奖励
      const result = await this.walletService.settleUserPendingRewards(accountSequence);

      if (result.settledCount > 0) {
        this.logger.log(
          `[PLANTING] Settled ${result.settledCount} pending rewards for ${accountSequence}: ` +
          `${result.totalUsdt} USDT, ${result.totalHashpower} hashpower`,
        );
      } else {
        this.logger.debug(`[PLANTING] No pending rewards to settle for ${accountSequence}`);
      }
    } catch (error) {
      this.logger.error(`[PLANTING] Failed to process planting for ${accountSequence}`, error);
      // 不抛出异常，避免阻塞 Kafka 消费
    }
  }
}
