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

/**
 * 引荐关系 CDC 事件处理器
 * 处理从引荐服务同步过来的引荐关系数据
 */
@Injectable()
export class ReferralSyncedHandler {
  private readonly logger = new Logger(ReferralSyncedHandler.name);

  constructor(
    private readonly syncedDataRepository: SyncedDataRepository,
    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 referral 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.upsertSyncedReferral({
        accountSequence: data.account_sequence || data.accountSequence,
        referrerAccountSequence: data.referrer_account_sequence || data.referrerAccountSequence || null,
        ancestorPath: data.ancestor_path || data.ancestorPath || null,
        depth: data.depth || 0,
        sourceSequenceNum: sequenceNum,
      });
    });

    this.logger.log(
      `Referral synced: ${data.account_sequence || data.accountSequence} -> ${data.referrer_account_sequence || data.referrerAccountSequence || 'none'}`,
    );
  }

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

    await this.syncedDataRepository.upsertSyncedReferral({
      accountSequence: data.account_sequence || data.accountSequence,
      referrerAccountSequence: data.referrer_account_sequence || data.referrerAccountSequence || null,
      ancestorPath: data.ancestor_path || data.ancestorPath || null,
      depth: data.depth || 0,
      sourceSequenceNum: sequenceNum,
    });

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

  private async handleDelete(data: any): Promise<void> {
    if (!data) return;
    // 引荐关系删除需要特殊处理
    this.logger.warn(`Referral delete event received: ${data.account_sequence || data.accountSequence}`);
  }
}
