/**
 * Push 多命名空间去重 — TransactionSynthesizer source_event_id 单元测试。
 *
 * 坐实:集团内同一条记录(同 subjectId + updatedAt),不同 source_unit(品牌/区域命名空间)
 * → 不同 source_event_id → 不会被去重折叠成一条(否则两品牌同号患者的事件会互相覆盖)。
 *
 * 纯函数测试,不跑 DB(去重最终由 patient_transactions partial UNIQUE 兜底,本测试验证 KEY 正确)。
 */
import { TransactionSynthesizer } from '../src/modules/sync/pipeline/transaction-synthesizer';
import type { EmitsConfig } from '../src/modules/sync/assembler/assembler.schema';

describe('push | 多命名空间去重(source_event_id)', () => {
  const synth = new TransactionSynthesizer();
  const emits: EmitsConfig = {
    action: 'appointment_created',
    subjectType: 'appointment',
    occurredAtField: 'occurredAt',
  };
  const make = (sourceUnit: string) => ({
    rawRow: {},
    emits,
    resource: 'appointments',
    hostId: 'h1',
    tenantId: 'grp_001',
    patientIdResolver: () => undefined,
    sourceContext: 'push:test',
    sourceUnit,
    canonicalRow: {
      externalId: 'apt-1',
      clinicId: 'C001',
      occurredAt: '2026-01-01T00:00:00+08:00',
      updatedAt: '2026-01-02T00:00:00+08:00',
    },
  });

  test('同 subjectId/updatedAt,不同 sourceUnit → 不同 source_event_id(不撞号)', () => {
    const a = synth.synthesize(make('瑞尔'));
    const b = synth.synthesize(make('瑞泰'));
    expect(a).not.toBeNull();
    expect(b).not.toBeNull();
    expect(a!.sourceEventId).not.toBe(b!.sourceEventId);
    expect(a!.sourceEventId).toContain(':瑞尔:');
    expect(b!.sourceEventId).toContain(':瑞泰:');
  });

  test('完全相同(含 sourceUnit)→ 同 source_event_id(会被去重)', () => {
    expect(synth.synthesize(make('瑞尔'))!.sourceEventId).toBe(
      synth.synthesize(make('瑞尔'))!.sourceEventId,
    );
  });

  test("单命名空间(sourceUnit='')→ key 稳定且不含品牌段", () => {
    expect(synth.synthesize(make(''))!.sourceEventId).toBe(
      'push:test:appointments::apt-1:2026-01-02T00:00:00+08:00',
    );
  });
});
