/**
 * 交易按日期分组（P4 时间线）：组内保持输入顺序，组头带当日收支小计。
 * 输入需已由调用方按日期倒序排列。
 */
import type { Transaction } from '../domain/types';
import { addDecimals, negateDecimal } from '../domain/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);
    const incomeAmounts: string[] = [];
    const expenseAmounts: string[] = [];
    for (const p of t.postings) {
      if (!p.amount) continue;
      if (p.account.startsWith('Income')) incomeAmounts.push(negateDecimal(p.amount));
      if (p.account.startsWith('Expenses')) expenseAmounts.push(p.amount);
    }
    if (incomeAmounts.length) group.income = addDecimals([group.income, ...incomeAmounts]);
    if (expenseAmounts.length) group.expense = addDecimals([group.expense, ...expenseAmounts]);
  }
  return groups;
}
