import { Controller, Logger, Inject } from '@nestjs/common';
import { EventPattern, Payload, Ctx, KafkaContext } from '@nestjs/microservices';
import { ContractSigningService } from '../../application/services/contract-signing.service';
import {
  IPlantingOrderRepository,
  PLANTING_ORDER_REPOSITORY,
} from '../../domain/repositories';
import { IdentityServiceClient } from '../external/identity-service.client';

/**
 * 认种事件消息结构
 */
interface PlantingEventMessage {
  eventName: string;
  aggregateId: string;
  occurredAt: string;
  data: {
    orderId: string;
    orderNo?: string;
    userId: string;
    accountSequence?: string;
    treeCount: number;
    totalAmount?: number;
    provinceCode?: string;
    cityCode?: string;
  };
}

/**
 * Identity Service 的用户信息响应
 */
interface UserKycInfo {
  phoneNumber?: string;
  realName?: string;
  idCardNumber?: string;
}

/**
 * 合同签署事件消费者
 *
 * 独立模块，监听 OrderPaid 事件来创建合同签署任务
 * 不影响现有的 planting-service 流程
 */
@Controller()
export class ContractSigningEventConsumer {
  private readonly logger = new Logger(ContractSigningEventConsumer.name);

  constructor(
    private readonly contractSigningService: ContractSigningService,
    @Inject(PLANTING_ORDER_REPOSITORY)
    private readonly orderRepo: IPlantingOrderRepository,
    private readonly identityServiceClient: IdentityServiceClient,
  ) {}

  /**
   * 监听认种事件
   * 当订单支付完成后（PlantingOrderPaid 事件），创建合同签署任务
   */
  @EventPattern('planting-events')
  async handlePlantingEvent(
    @Payload() message: PlantingEventMessage,
    @Ctx() context: KafkaContext,
  ): Promise<void> {
    const eventName = message.eventName;

    try {
      this.logger.debug(`[CONTRACT-SIGNING] Received event: ${eventName}`);

      // 处理 PlantingOrderPaid 事件（订单支付完成后触发）
      // 支持多种事件名称格式以确保兼容性
      if (
        eventName === 'PlantingOrderPaid' ||
        eventName === 'planting.order.paid' ||
        eventName === 'planting.tree.planted'
      ) {
        await this.handleOrderPaid(message);
      }
    } catch (error) {
      this.logger.error(`[CONTRACT-SIGNING] Error processing event ${eventName}:`, error);
      // 不抛出异常，避免影响其他消费者
    }
  }

  /**
   * 处理订单支付完成事件
   * 创建合同签署任务
   */
  private async handleOrderPaid(message: PlantingEventMessage): Promise<void> {
    const { data } = message;
    const orderNo = data.orderNo || data.orderId;

    this.logger.log(`[CONTRACT-SIGNING] Processing PlantingOrderPaid for order: ${orderNo}`);

    try {
      // 1. 获取订单详情
      const order = await this.orderRepo.findByOrderNo(orderNo);
      if (!order) {
        this.logger.warn(`[CONTRACT-SIGNING] Order not found: ${orderNo}`);
        return;
      }

      // 2. 获取用户 KYC 信息（只有实名认证通过的用户才能创建合同）
      const accountSequence = data.accountSequence || order.userId.toString();
      const kycInfo = await this.getUserKycInfo(accountSequence);

      if (!kycInfo) {
        this.logger.warn(
          `[CONTRACT-SIGNING] User ${accountSequence} has not completed KYC verification. Skipping contract creation for order: ${orderNo}`,
        );
        return;
      }

      // 3. 创建合同签署任务
      const provinceCitySelection = order.provinceCitySelection;
      if (!provinceCitySelection) {
        this.logger.warn(`[CONTRACT-SIGNING] Order ${orderNo} has no province/city selection`);
        return;
      }

      await this.contractSigningService.createSigningTask({
        orderNo,
        userId: order.userId,
        accountSequence,
        treeCount: order.treeCount.value,
        totalAmount: order.totalAmount,
        provinceCode: provinceCitySelection.provinceCode,
        provinceName: provinceCitySelection.provinceName,
        cityCode: provinceCitySelection.cityCode,
        cityName: provinceCitySelection.cityName,
        userPhoneNumber: kycInfo?.phoneNumber,
        userRealName: kycInfo?.realName,
        userIdCardNumber: kycInfo?.idCardNumber,
      });

      this.logger.log(`[CONTRACT-SIGNING] Created signing task for order: ${orderNo}`);
    } catch (error) {
      this.logger.error(`[CONTRACT-SIGNING] Failed to create signing task for order ${orderNo}:`, error);
      // 不抛出异常，合同签署任务创建失败不应影响主流程
    }
  }

  /**
   * 获取用户 KYC 信息
   */
  private async getUserKycInfo(accountSequence: string): Promise<UserKycInfo | null> {
    this.logger.debug(`[CONTRACT-SIGNING] Getting KYC info for accountSequence: ${accountSequence}`);
    try {
      const kycInfo = await this.identityServiceClient.getUserKycInfo(accountSequence);
      if (kycInfo) {
        this.logger.log(`[CONTRACT-SIGNING] Got KYC info for ${accountSequence}: realName=${kycInfo.realName ? '***' : 'null'}`);
      }
      return kycInfo;
    } catch (error) {
      this.logger.error(`[CONTRACT-SIGNING] Failed to get KYC info for ${accountSequence}:`, error);
      return null;
    }
  }
}
