import { describe, expect, it } from 'vitest';
import { groupTransactionsByDate } from '../src/components/transaction/transactionGroups';
import type { Transaction } from '../src/domain/core/types';

function tx(id: string, date: string, postings: { account: string; amount?: string }[]): Transaction {
  return {
    id, date, flag: '*', narration: id,
    postings: postings.map(p => ({ account: p.account, amount: p.amount, currency: 'CNY' })),
    tags: [], links: [], source: 'test', raw: '',
  };
}

describe('groupTransactionsByDate 日期分组', () => {
  it('同日合并并计算收支小计', () => {
    const groups = groupTransactionsByDate([
      tx('a', '2026-07-21', [{ account: 'Assets:招行', amount: '-35' }, { account: 'Expenses:餐饮', amount: '35' }]),
      tx('b', '2026-07-21', [{ account: 'Assets:招行', amount: '100' }, { account: 'Income:工资', amount: '-100' }]),
    ]);
    expect(groups).toHaveLength(1);
    expect(groups[0].date).toBe('2026-07-21');
    expect(groups[0].expense).toBe('35');
    expect(groups[0].income).toBe('100');
    expect(groups[0].items.map(t => t.id)).toEqual(['a', 'b']);
  });

  it('保持输入顺序（调用方已按日期倒序）', () => {
    const groups = groupTransactionsByDate([
      tx('a', '2026-07-21', [{ account: 'Expenses:餐饮', amount: '35' }]),
      tx('b', '2026-07-20', [{ account: 'Expenses:餐饮', amount: '20' }]),
    ]);
    expect(groups.map(g => g.date)).toEqual(['2026-07-21', '2026-07-20']);
  });

  it('转账日收支小计为零', () => {
    const groups = groupTransactionsByDate([
      tx('a', '2026-07-21', [{ account: 'Assets:A', amount: '-50' }, { account: 'Assets:B', amount: '50' }]),
    ]);
    expect(groups[0].income).toBe('0');
    expect(groups[0].expense).toBe('0');
  });

  it('空输入返回空数组', () => {
    expect(groupTransactionsByDate([])).toEqual([]);
  });
});
