import { Injectable, Logger } from '@nestjs/common';
import { Action, FactKind, FactStatus, FactType } from '@pac/types';
import type { FactDraft, Parser, ParserContext } from './parser.interface';

/**
 * ReferralParser — `referral_recorded` 解析器
 *
 * 产 1 个 `referral_record`(actual)— 老带新 / 渠道归因事实。
 * fact 挂在**被推荐人**(referee = fact.patient_id),表达"我是被 XXX 推荐来的"。
 * 推荐人(referrer)作为快照进 content(PAC 不维护 referrer 主数据;
 *  referrer 可能跨 host / 是员工,统一存名 + 类型即可,跟 emr.doctor_name 模式一致)。
 */
@Injectable()
export class ReferralParser implements Parser {
  readonly name = Action.REFERRAL_RECORDED;
  private readonly logger = new Logger(ReferralParser.name);

  parse(ctx: ParserContext): FactDraft[] {
    const c = ctx.canonicalRow;
    const externalId = String(c.externalId ?? ctx.transaction.subjectId).trim();
    if (!externalId) {
      this.logger.warn(
        `referral parser: missing externalId; tx=${ctx.transaction.id};skip`,
      );
      return [];
    }

    const recordedAt = c.recordedAt ? new Date(c.recordedAt as string) : null;
    const referrerExternalId = c.referrerExternalId
      ? String(c.referrerExternalId)
      : null;
    const referrerName = (c.referrerName as string | undefined) ?? null;
    const referrerChartNumber =
      (c.referrerChartNumber as string | undefined) ?? null;
    const referrerTypeRaw = (c.referrerType as string | undefined) ?? null;
    const referrerType = (
      ['patient', 'staff', 'partner', 'other'] as const
    ).includes(referrerTypeRaw as never)
      ? (referrerTypeRaw as 'patient' | 'staff' | 'partner' | 'other')
      : null;
    const channel = (c.channel as string | undefined) ?? null;

    return [
      {
        subjectId: `${FactType.REFERRAL_RECORD}:${externalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.REFERRAL_RECORD,
        status: FactStatus.ACTIVE,
        clinicId: ctx.transaction.clinicId,
        occurredAt: recordedAt,
        title: `转介绍来源 ${referrerName ?? referrerExternalId ?? '?'}${channel ? '(' + channel + ')' : ''}`,
        summary: null,
        content: {
          referral_external_id: externalId,
          referrer_external_id: referrerExternalId,
          referrer_name: referrerName,
          referrer_chart_number: referrerChartNumber,
          referrer_type: referrerType,
          channel,
        },
      },
    ];
  }
}
