import type { Budget, Transaction } from "./types";

export const categoryTemplates: Budget[] = [
  { category: "Wohnen", amount: 0, group: "Fixkosten" },
  { category: "Energie", amount: 0, group: "Fixkosten" },
  { category: "Versicherungen", amount: 0, group: "Fixkosten" },
  { category: "Telekom", amount: 0, group: "Fixkosten" },
  { category: "Internet", amount: 0, group: "Fixkosten" },
  { category: "Lebensmittel & Haushalt", amount: 0, group: "Fixkosten" },
  { category: "Gastronomie & Ausgehen", amount: 0, group: "Lifestyle" },
  { category: "Trafik", amount: 0, group: "Lifestyle" },
  { category: "Mobilität", amount: 0, group: "Fixkosten" },
  { category: "Abos", amount: 0, group: "Fixkosten" },
  { category: "Shopping", amount: 0, group: "Lifestyle" },
  { category: "Freizeit", amount: 0, group: "Lifestyle" },
  { category: "Sparen & Investieren", amount: 0, group: "Sparen" },
  { category: "Puffer", amount: 0, group: "Sparen" }
];

export function transactionBudgetAmount(t: Transaction) {
  if (t.is_internal_transfer) return 0;
  if (t.is_refund) return -Math.abs(t.amount);
  return Math.abs(t.amount);
}

export function monthSpend(transactions: Transaction[], month: string) {
  return transactions.filter(t => t.month === month).reduce((sum, t) => sum + transactionBudgetAmount(t), 0);
}

export function categorySpend(transactions: Transaction[], month: string, category: string) {
  return transactions.filter(t => t.month === month && t.category === category).reduce((sum, t) => sum + transactionBudgetAmount(t), 0);
}

export function lifestyleSummary(transactions: Transaction[], month: string, budgets: Budget[]) {
  const categories = budgets.filter(b => b.group === "Lifestyle").map(b => b.category);
  const total = budgets.filter(b => b.group === "Lifestyle").reduce((s, b) => s + b.amount, 0);
  const used = transactions.filter(t => t.month === month && categories.includes(t.category)).reduce((s, t) => s + transactionBudgetAmount(t), 0);
  return { total, used, remaining: Math.max(0, total - used) };
}

export function formatEUR(value: number) {
  return new Intl.NumberFormat("de-AT", { style: "currency", currency: "EUR", maximumFractionDigits: 2 }).format(value);
}
