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

/**
 * EncounterParser — `doctor_encounter_started` 解析器
 *
 * **v2.1 重塑**(canonical-fact-layer.md §四):
 *   encounter_record **退化为只装元数据**(doctor_id / notes / 时间锚点)。
 *   原嵌套的 diagnoses[] / treatments[] / next_steps[] **已拆出**:
 *     - 诊断 → diagnosis_record(由 DiagnosisParser 产)
 *     - 治疗 → treatment_record(由 TreatmentParser 产,合并旧 treatment_plan/review_plan)
 *     - 医生建议 → recommendation_record(由 RecommendationParser 产)
 *
 * 关联通过 `subject_id` + content.encounter_external_id 反查,不再嵌套。
 */
@Injectable()
export class EncounterParser implements Parser {
  readonly name = Action.DOCTOR_ENCOUNTER_STARTED;
  private readonly logger = new Logger(EncounterParser.name);

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

    const doctorId = (c.doctorId as string | undefined) ?? null;
    const doctorName = (c.doctorName as string | undefined) ?? null;
    const chiefComplaint = (c.chiefComplaint as string | undefined) ?? null;
    const encounterType = (c.encounterType as string | undefined) ?? null;
    const notes = (c.notes as string | undefined) ?? null;

    return [
      {
        subjectId: `${FactType.ENCOUNTER_RECORD}:${encExternalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.ENCOUNTER_RECORD,
        status: FactStatus.ACTIVE,
        clinicId: ctx.transaction.clinicId,
        occurredAt: ctx.transaction.occurredAt,
        title: `接诊 ${encExternalId}`,
        summary: chiefComplaint ?? notes ?? null,
        content: {
          encounter_external_id: encExternalId,
          doctor_id: doctorId,
          doctor_name: doctorName,
          chief_complaint: chiefComplaint,
          encounter_type: encounterType,
          notes,
        },
      },
    ];
  }
}
