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

/**
 * ConsultationParser — `consultation_created` 解析器
 *
 * 产 1 个 `consultation_record`(actual)= PAC 咨询主体(fact_consult_out)。
 *   intents = 患者咨询意向(potential_cure 解析,种植/正畸/洁牙…)→ 主观意愿信号(喂 treatment_intent)。
 *   ⚠️ 意向**不进召回**(召回只认医生诊断/建议);此处只忠实记录"患者来咨询想做啥"。
 */
@Injectable()
export class ConsultationParser implements Parser {
  readonly name = Action.CONSULTATION_CREATED;
  private readonly logger = new Logger(ConsultationParser.name);

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

    const occurredAt = c.occurredAt ? new Date(c.occurredAt as string) : null;
    const { intents, categories } = parsePotentialCure(c.intentRaw as string | null | undefined);
    const taskDirector = (c.taskDirector as string | undefined)?.trim() || null;
    const isFirstVisit =
      c.firstVisit === undefined || c.firstVisit === null
        ? null
        : String(c.firstVisit) === '1' || c.firstVisit === 1 || c.firstVisit === true;
    const consultDate = occurredAt ? occurredAt.toISOString().slice(0, 10) : null;
    const intentJoin = intents.length ? intents.join('/') : null;

    return [
      {
        subjectId: `${FactType.CONSULTATION_RECORD}:${externalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.CONSULTATION_RECORD,
        status: FactStatus.ACTIVE,
        clinicId: ctx.transaction.clinicId,
        occurredAt,
        title: `咨询${intentJoin ? '·' + intentJoin : ''}${isFirstVisit ? '(初诊)' : ''}`,
        summary: taskDirector ? `跟进:${taskDirector}` : null,
        content: {
          consultation_external_id: externalId,
          consult_date: consultDate,
          source_channel: null,
          intents,
          intent_categories: categories,
          is_first_visit: isFirstVisit,
          task_director: taskDirector,
          doctor_id: (c.doctorId as string | undefined) ?? null,
          appointment_external_id: (c.appointmentExternalId as string | undefined) ?? null,
          intent: intentJoin,
          content: null,
        },
      },
    ];
  }
}
