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

/**
 * OrderParser — `order_submitted`(医嘱提交)解析器(原 ChargeOrderParser)
 *
 * **v2 设计**:产 1 个 `order_record`,不再衍生 `payment_plan`
 * (是否未付清在 content.host_status / 应用层算 `sum(payments.amount)` < `order.total_amount`)。
 *
 * 医嘱 = 治疗服务 / 耗材 / 药品的统一单据(技耗分离):
 *   order_record.content.items[].type ∈ { treatment, consumable, medication, other }
 *
 * 状态(content.host_status):
 *   submitted    / partial_paid → fact.status='active'
 *   paid                        → fact.status='fulfilled'
 *   cancelled                   → fact.status='cancelled'
 */
@Injectable()
export class OrderParser implements Parser {
  readonly name = Action.ORDER_SUBMITTED;
  private readonly logger = new Logger(OrderParser.name);

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

    const hostStatus = String(c.status ?? 'submitted').toLowerCase();
    const recordStatus = OrderParser.STATUS_MAP[hostStatus] ?? FactStatus.ACTIVE;

    const totalAmount = Number(c.totalAmount ?? 0); // cents
    const createdAt = c.createdAt ? new Date(c.createdAt as string) : null;
    const items = Array.isArray(c.items) ? (c.items as Array<Record<string, unknown>>) : [];

    return [
      {
        subjectId: `${FactType.ORDER_RECORD}:${externalId}`,
        kind: FactKind.ACTUAL,
        type: FactType.ORDER_RECORD,
        status: recordStatus,
        clinicId: ctx.transaction.clinicId,
        occurredAt: createdAt,
        title: `医嘱 ${externalId}(¥${(totalAmount / 100).toFixed(2)})`,
        summary: items.length > 0 ? items.map((i) => i.name).filter(Boolean).join(' / ') : null,
        content: {
          order_external_id: externalId,
          total_amount: totalAmount,
          currency: (c.currency as string | undefined) ?? 'CNY',
          host_status: hostStatus,
          items: items.map((i) => ({
            name: i.name ?? null,
            /// 技耗分离:treatment(治疗服务) / consumable(耗材) / medication(药品) / other
            type: i.type ?? null,
            treatment_category: i.treatmentCategory ?? null,
            amount: typeof i.amount === 'number' ? i.amount : null,
          })),
        },
      },
    ];
  }

  // host status → FactStatus
  private static readonly STATUS_MAP: Record<string, FactStatus> = {
    submitted: FactStatus.ACTIVE,
    partial_paid: FactStatus.ACTIVE,
    paid: FactStatus.FULFILLED,
    cancelled: FactStatus.CANCELLED,
  };
}
