/**
 * 交易按日期分组（P4 时间线）：组内保持输入顺序，组头带当日收支小计。
 * 输入需已由调用方按日期倒序排列。
 */
import type { Transaction } from '../../domain/core/types';
import { addDecimals, negateDecimal } from '../../domain/core/decimal';

export interface DayGroup {
  date: string; // YYYY-MM-DD
  income: string;
  expense: string;
  items: Transaction[];
}

export function groupTransactionsByDate(txs: Transaction[]): DayGroup[] {
  const groups: DayGroup[] = [];
  const byDate = new Map<string, DayGroup>();
  for (const t of txs) {
    const date = t.date.slice(0, 10);
    let group = byDate.get(date);
    if (!group) {
      group = { date, income: '0', expense: '0', items: [] };
      byDate.set(date, group);
      groups.push(group);
    }
    group.items.push(t);
    // 直接累加到 group 字段，避免每笔交易创建临时数组
    for (const p of t.postings) {
      if (!p.amount) continue;
      if (p.account.startsWith('Income')) {
        group.income = addDecimals([group.income, negateDecimal(p.amount)]);
      } else if (p.account.startsWith('Expenses')) {
        group.expense = addDecimals([group.expense, p.amount]);
      }
    }
  }
  return groups;
}
