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

/**
 * VisitReceptionParser — `reception_completed` 解析器
 *
 * 产 1 个 `visit_reception_record`(actual)— 前台接待完成事实。
 */
@Injectable()
export class VisitReceptionParser implements Parser {
  readonly name = Action.RECEPTION_COMPLETED;
  private readonly logger = new Logger(VisitReceptionParser.name);

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

    const occurredAt = c.occurredAt ? new Date(c.occurredAt as string) : null;
    const receptionistId = (c.receptionistId as string | undefined) ?? null;

    return [
      {
        subjectId: `${FactType.VISIT_RECEPTION_RECORD}:${externalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.VISIT_RECEPTION_RECORD,
        status: FactStatus.ACTIVE,
        clinicId: ctx.transaction.clinicId,
        occurredAt,
        title: `前台接待 ${externalId}`,
        summary: receptionistId ? `接待:${receptionistId}` : null,
        content: {
          visit_reception_external_id: externalId,
          receptionist_id: receptionistId,
        },
      },
    ];
  }
}
