
import { BudgetData, Transaction } from '../types';

// 지출액 계산 (일일, 주간, 월간)
export const calculateSpentAmounts = (
  transactions: Transaction[],
  prevBudgetData: BudgetData
): BudgetData => {
  console.log("지출액 계산 시작, 트랜잭션 수:", transactions.length);
  
  // 지출 거래 필터링
  const expenseTransactions = transactions.filter(t => t.type === 'expense');
  
  // 오늘 지출 계산
  const todayExpenses = expenseTransactions.filter(t => {
    if (t.date && (t.date.includes('오늘') || t.date.includes('today'))) return true;
    return false;
  });
  const dailySpent = todayExpenses.reduce((sum, t) => sum + t.amount, 0);
  
  // 이번 주 지출 계산 (단순화된 버전)
  const weeklyExpenses = expenseTransactions.filter(t => {
    if (t.date && (
      t.date.includes('오늘') || 
      t.date.includes('today') || 
      t.date.includes('어제') || 
      t.date.includes('yesterday') || 
      t.date.includes('이번주') || 
      t.date.includes('this week')
    )) return true;
    return false;
  });
  const weeklySpent = weeklyExpenses.reduce((sum, t) => sum + t.amount, 0);
  
  // 이번 달 총 지출 계산 (모든 지출 트랜잭션)
  const monthlySpent = expenseTransactions.reduce((sum, t) => sum + t.amount, 0);

  // 기존 예산 목표 유지 (없으면 기본값 0)
  const dailyTarget = prevBudgetData?.daily?.targetAmount || 0;
  const weeklyTarget = prevBudgetData?.weekly?.targetAmount || 0;
  const monthlyTarget = prevBudgetData?.monthly?.targetAmount || 0;

  console.log("예산 목표 확인:", {
    일일: dailyTarget,
    주간: weeklyTarget,
    월간: monthlyTarget
  });

  // 예산 데이터 업데이트
  const updatedBudget = {
    daily: {
      targetAmount: dailyTarget,
      spentAmount: dailySpent,
      remainingAmount: Math.max(0, dailyTarget - dailySpent)
    },
    weekly: {
      targetAmount: weeklyTarget,
      spentAmount: weeklySpent,
      remainingAmount: Math.max(0, weeklyTarget - weeklySpent)
    },
    monthly: {
      targetAmount: monthlyTarget,
      spentAmount: monthlySpent,
      remainingAmount: Math.max(0, monthlyTarget - monthlySpent)
    }
  };
  
  console.log("지출액 계산 결과:", updatedBudget);
  
  return updatedBudget;
};
