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

/**
 * ConsultationParser — `consultation_created` 解析器
 *
 * 产 1 个 `consultation_record`(actual)— 咨询事实(400 / 接待中心 / 在线咨询入口)。
 * 启治召回(treatment_initiation_recall)的核心输入信号之一。
 */
@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 channel = (c.channel as string | undefined) ?? null;
    const notes = (c.notes as string | undefined) ?? null;

    return [
      {
        subjectId: `${FactType.CONSULTATION_RECORD}:${externalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.CONSULTATION_RECORD,
        status: FactStatus.ACTIVE,
        clinicId: ctx.transaction.clinicId,
        occurredAt,
        title: `咨询 ${externalId}${channel ? '(' + channel + ')' : ''}`,
        summary: notes,
        content: {
          consultation_external_id: externalId,
          channel,
          notes,
        },
      },
    ];
  }
}
