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

/**
 * value 患者价值 / LTV
 *
 * LTV(cents) = SUM(payment_record.amount) + SUM(recharge_record.amount) - SUM(refund_record.amount)
 *
 * 分档(可调,集中在此):
 *   ≥ ¥30,000  → VIP 钻卡    (score=4)
 *   ≥ ¥10,000  → VIP 金卡    (score=3)
 *   ≥ ¥3,000   → VIP 银卡    (score=2)
 *   ≥ ¥500     → 普通付费    (score=1)
 *   < ¥500     → 新客/未消费  (score=0)
 */
@Injectable()
export class ValueFeatureExtractor implements FeatureExtractor {
  readonly key = PersonaFeatureKey.VALUE;

  private static readonly TIERS = [
    { cents: 3000_000, label: 'VIP 钻卡', score: 4 },
    { cents: 1000_000, label: 'VIP 金卡', score: 3 },
    { cents: 300_000, label: 'VIP 银卡', score: 2 },
    { cents: 50_000, label: '普通付费', score: 1 },
  ];

  extract(ctx: FeatureExtractorContext): PersonaFeatureDraft | null {
    const payments = ctx.factsByType.get('payment_record') ?? [];
    const recharges = ctx.factsByType.get('recharge_record') ?? [];
    const refunds = ctx.factsByType.get('refund_record') ?? [];

    const factIds: string[] = [];
    let total = 0;
    for (const f of payments) {
      const c = f.content as Record<string, unknown>;
      // v2.1 字段统一为 amount_cents(payment.parser / payment fact-content-schemas)
      total += Number(c.amount_cents ?? c.amount ?? 0);
      factIds.push(f.id);
    }
    for (const f of recharges) {
      const c = f.content as Record<string, unknown>;
      total += Number(c.amount_cents ?? c.amount ?? 0);
      factIds.push(f.id);
    }
    for (const f of refunds) {
      const c = f.content as Record<string, unknown>;
      total -= Number(c.amount_cents ?? c.amount ?? 0);
      factIds.push(f.id);
    }

    const tier = ValueFeatureExtractor.TIERS.find((t) => total >= t.cents);
    const label = tier?.label ?? '新客/未消费';
    const score = tier?.score ?? 0;
    const yuan = (total / 100).toFixed(2);

    // description 简化 — UI 紧凑展示;笔数/退款明细走 facts 时间轴 / profile.paymentCount 等
    // (旧版 "新客/未消费(累计净消费 ¥58.00,含付款 1 笔 / 充值 0 笔 / 退款 0 笔)" UI 严重溢出)
    return {
      key: this.key,
      description: `${label} · 累计 ¥${yuan}`,
      score,
      evidence: { factIds },
    };
  }
}
