import { Injectable, Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrePlantingCdcEvent } from '../../infrastructure/kafka/pre-planting-cdc-consumer.service';
import { PrePlantingPrismaService } from '../../infrastructure/prisma/pre-planting-prisma.service';

/**
 * 预种持仓 CDC 事件处理器
 *
 * [2026-02-17] 新增：处理 cdc.pre-planting.public.pre_planting_positions 的 CDC 事件
 *
 * === 职责 ===
 * 同步预种持仓数据到 pre_planting_synced_positions 和 pre_planting_freeze_states 表。
 * 冻结调度器 (PrePlantingFreezeScheduler) 基于这些数据判断是否需要冻结/解冻。
 *
 * === 对现有系统的影响 ===
 * 零影响。本 handler 只写入预种独立表，不触碰任何现有表。
 */
@Injectable()
export class PrePlantingPositionSyncedHandler {
  private readonly logger = new Logger(PrePlantingPositionSyncedHandler.name);

  constructor(
    private readonly prePlantingPrisma: PrePlantingPrismaService,
  ) {}

  /**
   * 处理预种持仓 CDC 事件
   *
   * 注意：此 handler 在主 PrismaService 事务内执行（用于幂等性），
   * 但持仓同步写入的是 PrePlantingPrismaService 的表（事务外，最终一致性）。
   */
  async handle(
    event: PrePlantingCdcEvent,
    _tx: Prisma.TransactionClient,
  ): Promise<void> {
    const { op, before, after } = event.payload;
    const data = after || before;

    if (!data) {
      this.logger.warn(`[PRE-PLANTING-POSITION] Empty data, op=${op}`);
      return;
    }

    if (op === 'd') {
      this.logger.warn(`[PRE-PLANTING-POSITION] Delete event: userId=${data.user_id}`);
      return;
    }

    const userId = BigInt(data.user_id || data.userId || 0);
    const accountSequence = data.account_sequence || data.accountSequence;

    if (!accountSequence) {
      this.logger.warn(`[PRE-PLANTING-POSITION] Missing accountSequence for userId=${userId}`);
      return;
    }

    const totalPortions = data.total_portions || data.totalPortions || 0;
    const mergedPortions = data.merged_portions || data.mergedPortions || 0;
    const totalTreesMerged = data.total_trees_merged || data.totalTreesMerged || 0;
    const firstPurchaseAt = data.first_purchase_at || data.firstPurchaseAt;

    this.logger.log(
      `[PRE-PLANTING-POSITION] Sync: account=${accountSequence}, ` +
      `portions=${totalPortions}, merged=${totalTreesMerged}`,
    );

    // 同步到 PrePlantingSyncedPosition
    try {
      await this.prePlantingPrisma.prePlantingSyncedPosition.upsert({
        where: { userId },
        create: {
          userId,
          accountSequence,
          totalPortions,
          mergedPortions,
          totalTreesMerged,
          firstPurchaseAt: firstPurchaseAt ? new Date(firstPurchaseAt) : null,
          sourceTopic: event.topic,
          sourceOffset: event.offset,
        },
        update: {
          accountSequence,
          totalPortions,
          mergedPortions,
          totalTreesMerged,
          firstPurchaseAt: firstPurchaseAt ? new Date(firstPurchaseAt) : null,
          sourceTopic: event.topic,
          sourceOffset: event.offset,
          syncedAt: new Date(),
        },
      });
    } catch (error) {
      this.logger.error(`[PRE-PLANTING-POSITION] Failed to sync position`, error);
    }

    // 同步到 PrePlantingFreezeState（用于冻结调度器）
    try {
      await this.prePlantingPrisma.prePlantingFreezeState.upsert({
        where: { accountSequence },
        create: {
          accountSequence,
          totalPortions,
          totalTreesMerged,
          firstPurchaseAt: firstPurchaseAt ? new Date(firstPurchaseAt) : null,
        },
        update: {
          totalPortions,
          totalTreesMerged,
          firstPurchaseAt: firstPurchaseAt ? new Date(firstPurchaseAt) : null,
        },
      });
    } catch (error) {
      this.logger.error(`[PRE-PLANTING-POSITION] Failed to sync freeze state`, error);
    }
  }
}
