
import { supabase } from '@/lib/supabase';
import { Transaction } from '@/components/TransactionCard';
import { isSyncEnabled } from '@/utils/syncUtils';
import { toast } from '@/hooks/useToast.wrapper';

// Supabase와 거래 데이터 동기화
export const syncTransactionsWithSupabase = async (
  user: any, 
  transactions: Transaction[]
): Promise<Transaction[]> => {
  if (!user || !isSyncEnabled()) return transactions;
  
  try {
    const { data, error } = await supabase
      .from('transactions')
      .select('*')
      .eq('user_id', user.id);
      
    if (error) {
      console.error('Supabase 데이터 조회 오류:', error);
      return transactions;
    }
    
    if (data && data.length > 0) {
      // Supabase 데이터 로컬 형식으로 변환
      const supabaseTransactions = data.map(t => ({
        id: t.transaction_id || t.id,
        title: t.title,
        amount: t.amount,
        date: t.date,
        category: t.category,
        type: t.type
      }));
      
      // 로컬 데이터와 병합 (중복 ID 제거)
      const mergedTransactions = [...transactions];
      
      supabaseTransactions.forEach(newTx => {
        const existingIndex = mergedTransactions.findIndex(t => t.id === newTx.id);
        if (existingIndex >= 0) {
          mergedTransactions[existingIndex] = newTx;
        } else {
          mergedTransactions.push(newTx);
        }
      });
      
      return mergedTransactions;
    }
  } catch (err) {
    console.error('Supabase 동기화 오류:', err);
  }
  
  return transactions;
};

// Supabase에 트랜잭션 업데이트
export const updateTransactionInSupabase = async (
  user: any,
  transaction: Transaction
): Promise<void> => {
  if (!user || !isSyncEnabled()) return;
  
  try {
    const { error } = await supabase.from('transactions')
      .upsert({
        user_id: user.id,
        title: transaction.title,
        amount: transaction.amount,
        date: transaction.date,
        category: transaction.category,
        type: transaction.type,
        transaction_id: transaction.id
      });
      
    if (error) {
      console.error('트랜잭션 업데이트 오류:', error);
    }
  } catch (error) {
    console.error('Supabase 업데이트 오류:', error);
  }
};

// Supabase에서 트랜잭션 삭제
export const deleteTransactionFromSupabase = async (
  user: any,
  transactionId: string
): Promise<void> => {
  if (!user || !isSyncEnabled()) return;
  
  try {
    const { error } = await supabase.from('transactions')
      .delete()
      .eq('transaction_id', transactionId);
      
    if (error) {
      console.error('트랜잭션 삭제 오류:', error);
    }
  } catch (error) {
    console.error('Supabase 삭제 오류:', error);
  }
};
