
import { Transaction } from '@/contexts/budget/types';
import { parseTransactionDate } from '@/utils/dateParser';
import { format } from 'date-fns';

/**
 * 트랜잭션을 월별로 필터링
 */
export const filterTransactionsByMonth = (transactions: Transaction[], selectedMonth: string): Transaction[] => {
  if (!transactions || transactions.length === 0) {
    return [];
  }

  console.log(`월별 필터링 시작: ${selectedMonth}, 트랜잭션 수: ${transactions.length}`);
  
  try {
    const [year, month] = selectedMonth.split('-').map(Number);
    
    const filtered = transactions.filter(transaction => {
      const date = parseTransactionDate(transaction.date);
      
      if (!date) {
        console.warn(`날짜를 파싱할 수 없음: ${transaction.date}, 트랜잭션 ID: ${transaction.id}`);
        return false;
      }
      
      const transactionYear = date.getFullYear();
      const transactionMonth = date.getMonth() + 1; // JavaScript 월은 0부터 시작하므로 +1
      
      const match = transactionYear === year && transactionMonth === month;
      
      if (match) {
        console.log(`트랜잭션 매칭: ${transaction.id}, 제목: ${transaction.title}, 날짜: ${transaction.date}`);
      }
      
      return match;
    });
    
    console.log(`월별 필터링 결과: ${filtered.length}개 트랜잭션`);
    return filtered;
  } catch (error) {
    console.error('월별 필터링 중 오류:', error);
    return [];
  }
};

/**
 * 트랜잭션을 검색어로 필터링
 */
export const filterTransactionsByQuery = (transactions: Transaction[], searchQuery: string): Transaction[] => {
  if (!searchQuery || searchQuery.trim() === '') {
    return transactions;
  }
  
  const normalizedQuery = searchQuery.toLowerCase().trim();
  
  return transactions.filter(transaction => {
    const titleMatch = transaction.title.toLowerCase().includes(normalizedQuery);
    const categoryMatch = transaction.category.toLowerCase().includes(normalizedQuery);
    const amountMatch = transaction.amount.toString().includes(normalizedQuery);
    
    return titleMatch || categoryMatch || amountMatch;
  });
};

/**
 * 총 지출 계산 (지출 타입만 포함)
 */
export const calculateTotalExpenses = (transactions: Transaction[]): number => {
  if (!transactions || transactions.length === 0) {
    console.log('계산할 트랜잭션이 없습니다.');
    return 0;
  }
  
  console.log(`총 지출 계산 시작: 트랜잭션 ${transactions.length}개`);
  
  // 지출 타입만 필터링하고 합산
  const expenses = transactions
    .filter(t => t.type === 'expense')
    .reduce((sum, transaction) => {
      const amount = Number(transaction.amount);
      if (isNaN(amount)) {
        console.warn(`유효하지 않은 금액: ${transaction.amount}, 트랜잭션 ID: ${transaction.id}`);
        return sum;
      }
      return sum + amount;
    }, 0);
  
  console.log(`총 지출 계산 결과: ${expenses}원`);
  return expenses;
};

/**
 * 트랜잭션을 날짜별로 그룹화
 */
export const groupTransactionsByDate = (transactions: Transaction[]): Record<string, Transaction[]> => {
  const groups: Record<string, Transaction[]> = {};
  
  transactions.forEach(transaction => {
    const date = parseTransactionDate(transaction.date);
    if (!date) {
      console.warn(`날짜를 파싱할 수 없음: ${transaction.date}, 트랜잭션 ID: ${transaction.id}`);
      return;
    }
    
    const formattedDate = format(date, 'yyyy-MM-dd');
    
    if (!groups[formattedDate]) {
      groups[formattedDate] = [];
    }
    
    groups[formattedDate].push(transaction);
  });
  
  return groups;
};
