/**
 * traceRawSourceTable —— 回溯 assembler primary 表到「原始源表」,用于 push(source→匹配 assembler)
 * 与 reparse(rawPayload 属哪张源表)。重点回归:**union 多输入必须能收敛到同一根**,
 * 否则 union-primary 资源(refund_full)在 push/reparse 里被静默跳过(丢财务数据)。
 *
 * 跑:pnpm --filter @pac/service test -- trace-raw-source
 */
import { traceRawSourceTable } from '../src/modules/sync/cold-import/cold-import.service';

// 结算链最小 transforms:消费(filter 链)+ 退费整单(filter×2 + union)+ 退费明细(filter+lookup)
const transforms = [
  { kind: 'filter', input: 'patient_settlement', output: '_pay_hdr', where: {} },
  { kind: 'lookup', input: '_pay_hdr', output: 'payment_rows', from: 'settlement_modes', select: {} },
  { kind: 'filter', input: 'patient_settlement', output: '_refund_status4', where: {} },
  { kind: 'filter', input: 'patient_settlement', output: '_refund_neg3', where: {} },
  { kind: 'union', inputs: ['_refund_status4', '_refund_neg3'], output: 'refund_full_rows' },
  { kind: 'filter', input: 'patient_settlement_spec', output: '_refund_item_raw', where: {} },
  { kind: 'lookup', input: '_refund_item_raw', output: 'refund_item_rows', from: 'patient_settlement', select: {} },
  // route_by_pattern 多输出回同一 input
  { kind: 'route_by_pattern', input: '_treat_raw', outputs: [{ output: '_actual_raw' }, { output: '_rec_raw' }] },
];

describe('traceRawSourceTable', () => {
  it('单输入链:payment_rows → patient_settlement', () => {
    expect(traceRawSourceTable('payment_rows', transforms)).toBe('patient_settlement');
  });

  it('union 收敛:refund_full_rows 两路都回到 patient_settlement(修复点)', () => {
    expect(traceRawSourceTable('refund_full_rows', transforms)).toBe('patient_settlement');
  });

  it('lookup 链取 input(不取 from):refund_item_rows → patient_settlement_spec', () => {
    expect(traceRawSourceTable('refund_item_rows', transforms)).toBe('patient_settlement_spec');
  });

  it('route 多输出回同一 input:_actual_raw → _treat_raw', () => {
    expect(traceRawSourceTable('_actual_raw', transforms)).toBe('_treat_raw');
  });

  it('已是根表:原样返回', () => {
    expect(traceRawSourceTable('patient_settlement', transforms)).toBe('patient_settlement');
  });

  it('union 输入发散到多根 → 停在 union 输出(不误判)', () => {
    const diverge = [
      { kind: 'filter', input: 'table_a', output: '_a', where: {} },
      { kind: 'filter', input: 'table_b', output: '_b', where: {} },
      { kind: 'union', inputs: ['_a', '_b'], output: 'merged' },
    ];
    expect(traceRawSourceTable('merged', diverge)).toBe('merged');
  });
});
