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

/**
 * ComplaintParser — `complaint_filed` / `complaint_resolved` 解析器
 *
 * 产 1 个 `complaint_record`(actual)— 投诉事实。
 * 同 subject_id 在 filed → resolved 两次 transaction 间走版本流(supersede)。
 *
 * 合规重要性:Persona.do_not_contact_status 应消费 active complaint_record 触发 DNC。
 */
@Injectable()
export class ComplaintParser implements Parser {
  readonly name = Action.COMPLAINT_FILED;
  private readonly logger = new Logger(ComplaintParser.name);

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

    const filedAt = c.filedAt ? new Date(c.filedAt as string) : null;
    const resolved = ctx.transaction.action === Action.COMPLAINT_RESOLVED;
    const resolvedAt = c.resolvedAt ? new Date(c.resolvedAt as string) : null;
    const hostStatus = String(c.status ?? (resolved ? 'resolved' : 'open')).toLowerCase();
    const factStatus = hostStatus === 'resolved' ? FactStatus.FULFILLED : FactStatus.ACTIVE;

    return [
      {
        subjectId: `${FactType.COMPLAINT_RECORD}:${externalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.COMPLAINT_RECORD,
        status: factStatus,
        clinicId: ctx.transaction.clinicId,
        occurredAt: filedAt,
        title: `投诉 ${externalId}${resolved ? '(已结案)' : ''}`,
        summary: (c.content as string | undefined) ?? null,
        content: {
          complaint_external_id: externalId,
          host_status: hostStatus,
          category: c.category ?? null,
          content: c.content ?? null,
          related_treatment_subject_id: c.relatedTreatmentSubjectId ?? null,
          resolved_at: resolvedAt?.toISOString() ?? null,
        },
      },
    ];
  }
}
