/**
 * User Account Created Event Handler
 *
 * [2026-01-08] 新增：处理用户注册事件，自动创建钱包
 * 确保内部转账时接收方钱包一定存在
 *
 * 回滚方式: 删除此文件
 */

import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { WalletApplicationService } from '@/application/services';
import {
  IdentityEventConsumerService,
  UserAccountCreatedPayload,
} from '@/infrastructure/kafka/identity-event-consumer.service';

@Injectable()
export class UserAccountCreatedHandler implements OnModuleInit {
  private readonly logger = new Logger(UserAccountCreatedHandler.name);

  constructor(
    private readonly identityEventConsumer: IdentityEventConsumerService,
    private readonly walletService: WalletApplicationService,
  ) {}

  onModuleInit() {
    // 注册事件处理器
    this.identityEventConsumer.onUserAccountCreated(
      this.handleUserAccountCreated.bind(this),
    );
    this.logger.log(`[INIT] UserAccountCreatedHandler registered`);
  }

  /**
   * 处理用户账户创建事件
   * 在用户注册时自动创建钱包
   */
  private async handleUserAccountCreated(
    payload: UserAccountCreatedPayload,
  ): Promise<void> {
    const { userId, accountSequence } = payload;

    this.logger.log(
      `[HANDLE] Processing user account created: accountSequence=${accountSequence}, userId=${userId}`,
    );

    try {
      // 调用 walletService 确保钱包存在
      const result = await this.walletService.ensureWalletExists({
        accountSequence,
        userId,
      });

      if (result.existed) {
        this.logger.log(
          `[HANDLE] Wallet already exists for ${accountSequence}, walletId=${result.walletId}`,
        );
      } else {
        this.logger.log(
          `[HANDLE] Created new wallet for ${accountSequence}, walletId=${result.walletId}`,
        );
      }
    } catch (error) {
      this.logger.error(
        `[ERROR] Failed to create wallet for ${accountSequence}: ${error.message}`,
        error.stack,
      );
      // 重新抛出异常以触发 Kafka 重试
      throw error;
    }
  }
}
