import { Injectable } from '@nestjs/common';
import { PersonaFeatureKey } from '@pac/types';
import type {
  FeatureExtractor,
  FeatureExtractorContext,
  PersonaFeatureDraft,
} from './feature.interface';

/**
 * referral_champion 转介绍达人(B.1.2)— 规则层,lifetime(DW 累计计数器,单调只增)· v1
 *
 * 口径(图):识别有推荐能力且带来实质转化的客户。家庭型(带家人)/ 社交型(推外人)。
 *   有效转化:被推荐人结算排非治疗项后流水 > 200元(瑞尔)/100元(瑞泰)。
 *   家庭型:社交关系维护关联 ≥3 人且均有效转化;社交型:非同手机号推荐 ≥3 人且均有效转化。
 *
 * ⚠️ v1 用 DW 预聚合(fact_client_out):
 *   referralCount = recommend_num(推荐人数)、referralAmountCents = recommend_amount(带来转化总额)。
 *   —— 逐个被推荐人"均有效转化"需其本人结算(跨患者 + 需被推荐人已摄入),v1 用
 *      referralAmountCents>0(确实带来消费)作聚合代理;严格逐人阈值留 v2(全量 + 图谱预聚合)。
 *   家庭型/社交型:用 PatientRelation 直系家庭关系数 ≥3 区分(带家人 vs 推外人)。
 *   门槛不满足(推荐<3 或无转化额)→ 不打标签。
 */
@Injectable()
export class ReferralChampionFeatureExtractor implements FeatureExtractor {
  readonly key = PersonaFeatureKey.REFERRAL_CHAMPION;

  private static readonly FAMILY = new Set([
    'spouse',
    'child',
    'grandchild',
    'father',
    'mother',
    'grandparent',
  ]);
  private static readonly MIN_REFERRALS = 3;

  extract(ctx: FeatureExtractorContext): PersonaFeatureDraft | null {
    const count = ctx.profile?.referralCount ?? 0;
    const amountCents = ctx.profile?.referralAmountCents ?? 0;
    // 门槛:推荐 ≥3 人 且 带来实质转化(聚合额 > 0)
    if (count < ReferralChampionFeatureExtractor.MIN_REFERRALS || amountCents <= 0) return null;

    const familyCount = (ctx.relations ?? []).filter((r) =>
      ReferralChampionFeatureExtractor.FAMILY.has(r.relationship),
    ).length;

    const isFamily = familyCount >= ReferralChampionFeatureExtractor.MIN_REFERRALS;
    const code = isFamily ? 'family' : 'social';
    const zh = isFamily ? '家庭型' : '社交型';
    const yuan = Math.round(amountCents / 100).toLocaleString('zh-CN');

    return {
      key: this.key,
      description: `${zh} · 推荐${count}人 · 带来¥${yuan}`,
      score: null,
      data: {
        type: code,
        label: zh,
        referralCount: count,
        referralAmountCents: amountCents,
        familyRelations: familyCount,
      },
      evidence: { factIds: [] }, // 来自副表立柱(recommend_num/amount)+ 关系边
    };
  }
}
