
import { supabase } from '@/integrations/supabase/client';

/**
 * Normalization Service
 */
export async function normalizeTransaction({ transaction, clientId }) {
  let normalizedType = (transaction.transaction_type || '').trim().toLowerCase().replace(/\s+/g, '_');
  let rawCategoryKey = (transaction.category_key || '').trim().toLowerCase().replace(/\s+/g, '_');
  let normalizedCategoryKey = rawCategoryKey;
  let fundType = transaction.fund_type || 'operating';

  if (!rawCategoryKey) {
    return { normalizedType, normalizedCategoryKey, fundType };
  }

  try {
    let query = supabase
      .from('category_synonym_mappings')
      .select('normalized_category')
      .eq('raw_category', rawCategoryKey);
      
    if (clientId) {
      query = query.eq('client_id', clientId);
    } else {
      query = query.is('client_id', null);
    }
    
    const { data, error } = await query.limit(1).single();
    
    if (!error && data && data.normalized_category) {
      normalizedCategoryKey = data.normalized_category;
    }
  } catch (err) {
    console.warn("Synonym lookup failed, proceeding with raw category.", err);
  }

  if (!transaction.fund_type) {
    if (normalizedCategoryKey.includes('reserve') || normalizedType.includes('reserve')) {
      fundType = 'reserve';
    } else {
      fundType = 'operating';
    }
  }

  return { normalizedType, normalizedCategoryKey, fundType };
}
