import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { Kafka, Consumer, EachMessagePayload } from 'kafkajs';
import { ReferralService } from '../services/referral.service';

interface UserRegisteredPayload {
  userId: string;
  phone: string | null;
  email: string | null;
  role: string;
  referralCode: string | null; // 注册时填写的推荐码 (推荐人的码)
  timestamp: string;
}

/**
 * 监听 auth-service 发布的 genex.user.registered 事件
 * 自动为新用户创建推荐档案
 */
@Injectable()
export class UserRegisteredHandler implements OnModuleInit {
  private readonly logger = new Logger(UserRegisteredHandler.name);
  private consumer: Consumer;

  constructor(private readonly referralService: ReferralService) {}

  async onModuleInit() {
    const brokers = (process.env.KAFKA_BROKERS || 'localhost:9092').split(',').map((b) => b.trim());
    const kafka = new Kafka({
      clientId: 'referral-service',
      brokers,
      retry: { retries: 5 },
    });

    this.consumer = kafka.consumer({ groupId: 'genex-referral-service' });

    try {
      await this.consumer.connect();
      await this.consumer.subscribe({
        topic: 'genex.user.registered',
        fromBeginning: false,
      });

      await this.consumer.run({
        eachMessage: async (payload: EachMessagePayload) => {
          await this.handleMessage(payload);
        },
      });

      this.logger.log('已订阅 genex.user.registered');
    } catch (err) {
      // Kafka 不可用时不阻断服务启动
      this.logger.warn(`Kafka 连接失败 (将跳过事件监听): ${err.message}`);
    }
  }

  private async handleMessage(payload: EachMessagePayload): Promise<void> {
    const raw = payload.message.value?.toString();
    if (!raw) return;

    let event: UserRegisteredPayload;
    try {
      event = JSON.parse(raw);
    } catch {
      this.logger.error('事件消息解析失败');
      return;
    }

    if (!event.userId) {
      this.logger.warn('无效事件: 缺少 userId');
      return;
    }

    try {
      await this.referralService.createProfile({
        userId: event.userId,
        usedCode: event.referralCode ?? null,
      });
    } catch (err) {
      this.logger.error(`创建推荐档案失败 userId=${event.userId}: ${err.message}`);
      // 不 rethrow — 避免死锁，允许 Kafka 继续消费
    }
  }

  async onModuleDestroy() {
    try {
      await this.consumer?.disconnect();
    } catch {
      // ignore
    }
  }
}
