/**
 * dedup 低置信度对手方约束 & transferRecognizer 方向归类测试。
 * 验证 #7/#10 修复。
 */
import { describe, expect, it } from 'vitest';
import { checkDuplicate, batchDedup, type DedupConfig, DEFAULT_DEDUP_CONFIG } from '../src/domain/transaction/dedup';
import { recognizeTransfers, type TransferConfig, DEFAULT_TRANSFER_CONFIG } from '../src/domain/transaction/transferRecognizer';
import type { ImportedEvent } from '../src/domain/core/types';

// ============ dedup 低置信度对手方约束 ============

describe('dedup 低置信度对手方约束 (#7)', () => {
  const config: DedupConfig = DEFAULT_DEDUP_CONFIG;

  const makeEvent = (overrides: Partial<ImportedEvent>): ImportedEvent => ({
    id: 'test-id',
    occurredAt: '2026-07-01 12:00:00',
    amount: '100.00',
    currency: 'CNY',
    direction: 'expense',
    counterparty: '星巴克',
    memo: '',
    raw: {},
    ...overrides,
  });

  const makeHistoryItem = (overrides: Partial<ImportedEvent>): ImportedEvent => ({
    id: 'hist-id',
    occurredAt: '2026-07-01',
    amount: '100.00',
    currency: 'CNY',
    direction: 'expense',
    counterparty: '星巴克',
    memo: '',
    raw: {},
    ...overrides,
  });

  it('同天+同金额+同对手方 → medium 置信度重复', () => {
    const event = makeEvent({ occurredAt: '2026-07-01 10:00:00' });
    const history = [makeHistoryItem({ occurredAt: '2026-07-01' })];

    const result = checkDuplicate(event, history, config);
    expect(result.isDuplicate).toBe(true);
    expect(result.confidence).toBe('medium');
  });

  it('同天+同金额+双方对手方不同 → 非重复（避免误杀）', () => {
    const event = makeEvent({
      occurredAt: '2026-07-01 10:00:00',
      counterparty: '星巴克',
    });
    const history = [makeHistoryItem({
      occurredAt: '2026-07-01',
      counterparty: '瑞幸咖啡', // 不同对手方
    })];

    const result = checkDuplicate(event, history, config);
    expect(result.isDuplicate).toBe(false);
  });

  it('同天+同金额+一方无对手方 → low 置信度重复', () => {
    const event = makeEvent({
      occurredAt: '2026-07-01 10:00:00',
      counterparty: '星巴克',
    });
    const history = [makeHistoryItem({
      occurredAt: '2026-07-01',
      counterparty: '', // 无对手方
    })];

    const result = checkDuplicate(event, history, config);
    expect(result.isDuplicate).toBe(true);
    expect(result.confidence).toBe('low');
  });

  it('同天+同金额+双方都无对手方 → medium 置信度重复（sameCounterparty=true）', () => {
    const event = makeEvent({
      occurredAt: '2026-07-01 10:00:00',
      counterparty: '',
    });
    const history = [makeHistoryItem({
      occurredAt: '2026-07-01',
      counterparty: '',
    })];

    const result = checkDuplicate(event, history, config);
    expect(result.isDuplicate).toBe(true);
    // 双方都无对手方时 sameCounterparty=true，返回 medium
    expect(result.confidence).toBe('medium');
  });

  it('batchDedup 中同天同金额不同对手方的事件都保留', () => {
    const events: ImportedEvent[] = [
      makeEvent({ id: 'e1', occurredAt: '2026-07-01 10:00:00', counterparty: '星巴克', amount: '30.00' }),
      makeEvent({ id: 'e2', occurredAt: '2026-07-01 14:00:00', counterparty: '瑞幸咖啡', amount: '30.00' }),
    ];

    const result = batchDedup(events, config);
    // 两笔不同对手方的交易都应该保留
    expect(result.accepted.length).toBe(2);
    expect(result.duplicates.length).toBe(0);
  });
});

// ============ transferRecognizer 方向归类 ============

describe('transferRecognizer transfer 方向归类 (#10)', () => {
  const config: TransferConfig = DEFAULT_TRANSFER_CONFIG;

  const makeEvent = (overrides: Partial<ImportedEvent>): ImportedEvent => ({
    id: 'test-id',
    occurredAt: '2026-07-01 12:00:00',
    amount: '100.00',
    currency: 'CNY',
    direction: 'transfer',
    counterparty: '转账',
    memo: '',
    raw: {},
    ...overrides,
  });

  it('transfer 事件按金额正负归类：负数=支出，正数=收入', () => {
    const events: ImportedEvent[] = [
      makeEvent({ id: 'out', amount: '-500.00', occurredAt: '2026-07-01 10:00:00', counterparty: '转出到银行卡' }),
      makeEvent({ id: 'in', amount: '500.00', occurredAt: '2026-07-01 10:00:05', counterparty: '从支付宝转入' }),
    ];

    const result = recognizeTransfers(events, config);
    // 应该识别为一笔转账
    expect(result.transfers.length).toBe(1);
    // TransferPair 使用 leftEventId/rightEventId
    expect(result.transfers[0].leftEventId).toBe('out');
    expect(result.transfers[0].rightEventId).toBe('in');
  });

  it('同一 transfer 事件不会同时出现在收入和支出列表', () => {
    // 单笔 transfer 事件（只有支出方）
    const events: ImportedEvent[] = [
      makeEvent({ id: 'single', amount: '-100.00', occurredAt: '2026-07-01 10:00:00' }),
    ];

    const result = recognizeTransfers(events, config);
    // 没有配对，不应该识别为转账
    expect(result.transfers.length).toBe(0);
    // 事件应该保留在 remaining 中
    expect(result.remaining.length).toBe(1);
  });

  it('income + expense 正常配对', () => {
    const events: ImportedEvent[] = [
      makeEvent({ id: 'exp', direction: 'expense', amount: '-200.00', occurredAt: '2026-07-01 10:00:00' }),
      makeEvent({ id: 'inc', direction: 'income', amount: '200.00', occurredAt: '2026-07-01 10:00:03' }),
    ];

    const result = recognizeTransfers(events, config);
    expect(result.transfers.length).toBe(1);
    expect(result.transfers[0].leftEventId).toBe('exp');
    expect(result.transfers[0].rightEventId).toBe('inc');
  });

  it('时间窗口外的不配对', () => {
    const events: ImportedEvent[] = [
      makeEvent({ id: 'exp', direction: 'expense', amount: '-200.00', occurredAt: '2026-07-01 10:00:00' }),
      makeEvent({ id: 'inc', direction: 'income', amount: '200.00', occurredAt: '2026-07-05 10:00:00' }), // 4天后
    ];

    const result = recognizeTransfers(events, config);
    // 默认时间窗口是 72 小时（3天），4天外的不配对
    expect(result.transfers.length).toBe(0);
    expect(result.remaining.length).toBe(2);
  });
});
