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

/**
 * RechargeParser — `recharge_received` 解析器
 *
 * 产 1 个 `recharge_record`(actual)— 充值/储值/福利卡办理事实。
 * Persona.value(LTV / VIP 识别)累计 recharge.amount + payment.amount - refund.amount。
 */
@Injectable()
export class RechargeParser implements Parser {
  readonly name = Action.RECHARGE_RECEIVED;
  private readonly logger = new Logger(RechargeParser.name);

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

    const amount = Number(c.amount ?? 0); // cents
    const rechargedAt = c.rechargedAt ? new Date(c.rechargedAt as string) : null;
    const rechargeType = (c.rechargeType as string | undefined) ?? null;
    const benefits = c.benefits ?? null;

    return [
      {
        subjectId: `${FactType.RECHARGE_RECORD}:${externalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.RECHARGE_RECORD,
        status: FactStatus.ACTIVE,
        clinicId: ctx.transaction.clinicId,
        occurredAt: rechargedAt,
        title: `充值 ¥${(amount / 100).toFixed(2)}${rechargeType ? '(' + rechargeType + ')' : ''}`,
        summary: null,
        content: {
          recharge_external_id: externalId,
          amount,
          currency: (c.currency as string | undefined) ?? 'CNY',
          recharge_type: rechargeType,
          benefits,
        },
      },
    ];
  }
}
