import { Injectable, Logger } from '@nestjs/common';
import { CDCEvent } from '../../infrastructure/kafka/cdc-consumer.service';
import { SyncedDataRepository } from '../../infrastructure/persistence/repositories/synced-data.repository';
import { ContributionAccountRepository } from '../../infrastructure/persistence/repositories/contribution-account.repository';
import { ContributionAccountAggregate } from '../../domain/aggregates/contribution-account.aggregate';
import { UnitOfWork } from '../../infrastructure/persistence/unit-of-work/unit-of-work';

/**
 * 用户 CDC 事件处理器
 * 处理从身份服务同步过来的用户数据
 */
@Injectable()
export class UserSyncedHandler {
  private readonly logger = new Logger(UserSyncedHandler.name);

  constructor(
    private readonly syncedDataRepository: SyncedDataRepository,
    private readonly contributionAccountRepository: ContributionAccountRepository,
    private readonly unitOfWork: UnitOfWork,
  ) {}

  async handle(event: CDCEvent): Promise<void> {
    const { op, before, after } = event.payload;

    try {
      switch (op) {
        case 'c': // create
        case 'r': // read (snapshot)
          await this.handleCreate(after, event.sequenceNum);
          break;
        case 'u': // update
          await this.handleUpdate(after, event.sequenceNum);
          break;
        case 'd': // delete
          await this.handleDelete(before);
          break;
        default:
          this.logger.warn(`Unknown CDC operation: ${op}`);
      }
    } catch (error) {
      this.logger.error(`Failed to handle user CDC event`, error);
      throw error;
    }
  }

  private async handleCreate(data: any, sequenceNum: bigint): Promise<void> {
    if (!data) return;

    await this.unitOfWork.executeInTransaction(async () => {
      // 保存同步的用户数据
      await this.syncedDataRepository.upsertSyncedUser({
        originalUserId: BigInt(data.id),
        accountSequence: data.account_sequence || data.accountSequence,
        phone: data.phone || null,
        status: data.status || 'ACTIVE',
        sourceSequenceNum: sequenceNum,
      });

      // 为用户创建算力账户（如果不存在）
      const accountSequence = data.account_sequence || data.accountSequence;
      const existingAccount = await this.contributionAccountRepository.findByAccountSequence(accountSequence);

      if (!existingAccount) {
        const newAccount = ContributionAccountAggregate.create(accountSequence);
        await this.contributionAccountRepository.save(newAccount);
        this.logger.log(`Created contribution account for user: ${accountSequence}`);
      }
    });

    this.logger.debug(`User synced: ${data.account_sequence || data.accountSequence}`);
  }

  private async handleUpdate(data: any, sequenceNum: bigint): Promise<void> {
    if (!data) return;

    await this.syncedDataRepository.upsertSyncedUser({
      originalUserId: BigInt(data.id),
      accountSequence: data.account_sequence || data.accountSequence,
      phone: data.phone || null,
      status: data.status || 'ACTIVE',
      sourceSequenceNum: sequenceNum,
    });

    this.logger.debug(`User updated: ${data.account_sequence || data.accountSequence}`);
  }

  private async handleDelete(data: any): Promise<void> {
    if (!data) return;
    // 用户删除一般不处理，保留历史数据
    this.logger.debug(`User delete event received: ${data.account_sequence || data.accountSequence}`);
  }
}
