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

/**
 * RefundParser — `refund_created` 解析器
 *
 * 产 1 个 `refund_record`(actual)— 退费事实。
 * Persona.value(LTV)= sum(payment.amount) + sum(recharge.amount) - sum(refund.amount)。
 */
@Injectable()
export class RefundParser implements Parser {
  readonly name = Action.REFUND_CREATED;
  private readonly logger = new Logger(RefundParser.name);

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

    // Math.abs 归一:host 退费两种表达
    //   ① is_refund=1 → settlement_money 通常 > 0(被退金额本身)
    //   ② settlement_status=4 → settlement_money 通常 < 0(反向冲减)
    // 业务语义统一为正 cents = "患者拿回的钱"
    const amount = Math.abs(Number(c.amount ?? 0)); // cents
    const refundedAt = c.refundedAt ? new Date(c.refundedAt as string) : null;
    const paymentExternalId = (c.paymentExternalId as string | undefined) ?? null;
    const reason = (c.reason as string | undefined) ?? null;

    return [
      {
        subjectId: `${FactType.REFUND_RECORD}:${externalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.REFUND_RECORD,
        status: FactStatus.ACTIVE,
        clinicId: ctx.transaction.clinicId,
        occurredAt: refundedAt,
        title: `退费 ¥${(amount / 100).toFixed(2)}`,
        summary: reason,
        content: {
          refund_external_id: externalId,
          amount_cents: amount,                       // schema 要 amount_cents(W3 末 jvs-dw 接入时修正)
          related_payment_external_id: paymentExternalId, // schema 要 related_payment_external_id
          reason,
        },
      },
    ];
  }
}
