
import { Transaction } from '@/components/TransactionCard';
import { MONTHS_KR } from './dateUtils';

// 월별 거래 필터링
export const filterTransactionsByMonth = (transactions: Transaction[], selectedMonth: string): Transaction[] => {
  console.log('월별 필터링:', selectedMonth, '트랜잭션 수:', transactions.length);
  
  // 현재 날짜 정보
  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = now.getMonth() + 1; // JavaScript 월은 0부터 시작
  
  // 선택된 월의 인덱스 (0-11)
  const selectedMonthIndex = MONTHS_KR.findIndex(month => month === selectedMonth);
  
  // 특수 케이스 처리: '이번 달', '오늘', '이번 주' 등
  if (transactions.some(t => t.date.includes('오늘') || t.date.includes('어제') || t.date.includes('이번주'))) {
    return transactions;
  }
  
  // 실제 필터링
  return transactions.filter(transaction => {
    // 날짜 형식이 '2023-05-15' 또는 '2023/05/15' 등의 형식인 경우
    if (transaction.date.includes('-') || transaction.date.includes('/')) {
      const parts = transaction.date.split(/[-\/]/);
      if (parts.length >= 2) {
        const transactionMonth = parseInt(parts[1]);
        const monthIndex = transactionMonth - 1; // 0-11 인덱스로 변환
        return monthIndex === selectedMonthIndex;
      }
    }
    
    // 날짜에 월이 포함된 경우 (예: '5월 15일')
    for (let i = 0; i < MONTHS_KR.length; i++) {
      if (transaction.date.includes(MONTHS_KR[i])) {
        return MONTHS_KR[i] === selectedMonth;
      }
    }
    
    // 기본적으로 모든 트랜잭션 표시 (필터링 실패 시)
    return true;
  });
};

// 검색어로 거래 필터링
export const filterTransactionsByQuery = (transactions: Transaction[], query: string): Transaction[] => {
  if (!query.trim()) return transactions;
  
  const lowercaseQuery = query.toLowerCase();
  return transactions.filter(transaction => 
    transaction.title.toLowerCase().includes(lowercaseQuery) ||
    transaction.category.toLowerCase().includes(lowercaseQuery) ||
    transaction.amount.toString().includes(lowercaseQuery)
  );
};

// 총 지출 계산
export const calculateTotalExpenses = (transactions: Transaction[]): number => {
  return transactions
    .filter(t => t.type === 'expense')
    .reduce((total, transaction) => total + transaction.amount, 0);
};
