import { Controller, Logger } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices';
import { RewardApplicationService } from '../../application/services/reward-application.service';
import { EventAckPublisher } from './event-ack.publisher';

/**
 * 认种订单支付事件（正常奖励分配流程）
 * 由 referral-service 在收到 contract.signed 后转发
 */
interface PlantingOrderPaidEvent {
  eventName?: string;
  data?: {
    orderId: string;
    userId: string;
    accountSequence?: string; // 跨服务关联标识（优先使用）
    treeCount: number;
    provinceCode: string;
    cityCode: string;
    paidAt: string;
    // [2026-02-26] 总部运营成本压力涨价（每棵树加价金额），归总部 (S0000000001)
    priceSupplement?: number;
    totalAmount?: number;
  };
  // 兼容旧格式
  orderId?: string;
  userId?: string;
  accountSequence?: string;
  treeCount?: number;
  provinceCode?: string;
  cityCode?: string;
  paidAt?: string;
  // B方案：outbox 元数据
  _outbox?: {
    id: string;
    aggregateId: string;
    eventType: string;
  };
}

/**
 * 认种订单过期事件（合同超时未签署，系统账户分配）
 * 由 referral-service 在收到 contract.expired 后转发
 */
interface PlantingOrderExpiredEvent {
  eventName: string;
  data: {
    orderId: string;
    userId: string;
    accountSequence: string;
    treeCount: number;
    provinceCode: string;
    cityCode: string;
    expiredAt: string;
  };
}

@Controller()
export class EventConsumerController {
  private readonly logger = new Logger(EventConsumerController.name);

  constructor(
    private readonly rewardService: RewardApplicationService,
    private readonly eventAckPublisher: EventAckPublisher,
  ) {}

  /**
   * 监听认种订单支付成功事件
   *
   * 由 referral-service 在收到 contract.signed 后转发
   * 触发正常奖励分配（与原流程完全一致）
   */
  @MessagePattern('planting.order.paid')
  async handlePlantingOrderPaid(@Payload() message: PlantingOrderPaidEvent) {
    this.logger.log(`Received planting.order.paid event: ${JSON.stringify(message)}`);

    // 解析消息数据（支持新旧格式）
    const eventData = message.data || {
      orderId: message.orderId!,
      userId: message.userId!,
      accountSequence: message.accountSequence,
      treeCount: message.treeCount!,
      provinceCode: message.provinceCode!,
      cityCode: message.cityCode!,
      paidAt: message.paidAt!,
    };

    // B方案：提取 outbox 信息用于发送确认
    const outboxInfo = message._outbox;
    const eventId = outboxInfo?.aggregateId || eventData.orderId;

    try {
      // 1. 计算并分配奖励（正常流程，100% 不变）
      await this.rewardService.distributeRewards({
        sourceOrderNo: eventData.orderId,
        sourceUserId: BigInt(eventData.userId),
        sourceAccountSequence: eventData.accountSequence,
        treeCount: eventData.treeCount,
        provinceCode: eventData.provinceCode,
        cityCode: eventData.cityCode,
        priceSupplement: eventData.priceSupplement || 0,
      });

      // 2. 检查该用户是否有待领取奖励需要转为可结算
      if (eventData.accountSequence) {
        await this.rewardService.claimPendingRewardsForAccountSequence(eventData.accountSequence);
      }

      this.logger.log(`Successfully distributed rewards for order ${eventData.orderId}`);

      // B方案：发送处理成功确认
      if (outboxInfo) {
        await this.eventAckPublisher.sendSuccess(eventId, outboxInfo.eventType);
      }
    } catch (error) {
      this.logger.error(`Error processing planting.order.paid:`, error);

      // B方案：发送处理失败确认
      if (outboxInfo) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        await this.eventAckPublisher.sendFailure(eventId, outboxInfo.eventType, errorMessage);
      }

      throw error;
    }
  }

  /**
   * 监听认种订单过期事件（合同超时未签署）
   *
   * 由 referral-service 在收到 contract.expired 后转发
   * 触发系统账户奖励分配：
   * - 系统费用（成本费、运营费、底池、总部基础费）：正常分配
   * - 用户权益（分享、省团队、市团队、社区、省区域、市区域）：全部进入系统默认账户
   */
  @MessagePattern('planting.order.expired')
  async handlePlantingOrderExpired(@Payload() message: PlantingOrderExpiredEvent) {
    this.logger.log(`Received planting.order.expired event: ${JSON.stringify(message)}`);

    const eventData = message.data;

    try {
      this.logger.warn(
        `Order ${eventData.orderId} expired (contract not signed within 24h), ` +
        `accountSequence: ${eventData.accountSequence}, expiredAt: ${eventData.expiredAt}. ` +
        `Starting system account distribution (user rights go to default system accounts)...`,
      );

      // 分配奖励到系统账户（用户权益进入系统默认账户）
      await this.rewardService.distributeRewardsForExpiredContract({
        sourceOrderNo: eventData.orderId,
        sourceUserId: BigInt(eventData.userId),
        sourceAccountSequence: eventData.accountSequence,
        treeCount: eventData.treeCount,
        provinceCode: eventData.provinceCode,
        cityCode: eventData.cityCode,
      });

      this.logger.log(`Successfully distributed rewards to system accounts for expired order ${eventData.orderId}`);
    } catch (error) {
      this.logger.error(`Error processing planting.order.expired for order ${eventData.orderId}:`, error);
      throw error;
    }
  }
}
