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

/**
 * VisitRegistrationParser — `visit_registered` 解析器
 *
 * 产 1 个 `visit_registration_record`(actual)— 挂号事实。
 */
@Injectable()
export class VisitRegistrationParser implements Parser {
  readonly name = Action.VISIT_REGISTERED;
  private readonly logger = new Logger(VisitRegistrationParser.name);

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

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

    return [
      {
        subjectId: `${FactType.VISIT_REGISTRATION_RECORD}:${externalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.VISIT_REGISTRATION_RECORD,
        status: FactStatus.ACTIVE,
        clinicId: ctx.transaction.clinicId,
        occurredAt,
        title: `挂号 ${externalId}`,
        summary: appointmentExternalId ? `关联预约:${appointmentExternalId}` : null,
        content: {
          visit_registration_external_id: externalId,
          appointment_external_id: appointmentExternalId,
        },
      },
    ];
  }
}
