/**
 * 净资产计算（plan.md「5.2 净资产趋势」）。
 */

import { addDecimals, subtractDecimals, compareDecimals, negateDecimal } from '../core/decimal';
import type { Transaction } from '../core/types';

export interface NetWorthPoint {
  date: string;
  assets: string;
  liabilities: string;
  netWorth: string;
}

/** 按账户类型分组计算余额。 */
export function calculateBalanceByType(
  transactions: Transaction[],
  accountType: 'Assets' | 'Liabilities' | 'Income' | 'Expenses' | 'Equity',
): string {
  const relevant = transactions.filter(t =>
    t.postings.some(p => p.account.startsWith(accountType))
  );
  const amounts: string[] = [];
  for (const t of relevant) {
    for (const p of t.postings) {
      if (p.account.startsWith(accountType) && p.amount) {
        amounts.push(p.amount);
      }
    }
  }
  return addDecimals(amounts);
}

/** 计算某时点的资产/负债/净资产。 */
export function calculateNetWorth(
  transactions: Transaction[],
  asOfDate?: string,
): { assets: string; liabilities: string; netWorth: string } {
  const filtered = asOfDate
    ? transactions.filter(t => t.date.slice(0, 10) <= asOfDate)
    : transactions;

  const assets = calculateBalanceByType(filtered, 'Assets');
  const liabilities = calculateBalanceByType(filtered, 'Liabilities');
  // 负债账户正常是负余额，取绝对值
  const liabAbs = compareDecimals(liabilities, '0') < 0 ? negateDecimal(liabilities) : liabilities;
  const netWorth = subtractDecimals(assets, liabAbs);
  return { assets, liabilities: liabAbs, netWorth };
}

/** 计算净资产趋势（按日期序列）。 */
export function calculateNetWorthTrend(
  transactions: Transaction[],
  dates: string[],
): NetWorthPoint[] {
  return dates.map(date => {
    const { assets, liabilities, netWorth } = calculateNetWorth(transactions, date);
    return { date, assets, liabilities, netWorth };
  });
}
