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

export async function analyzeRestorationCandidates() {
  try {
    const { data: expenses, error } = await supabase
      .from('expenses')
      .select('*')
      .not('billable_type', 'is', null)
      .order('date', { ascending: false });

    if (error) throw error;

    const issues = expenses.filter(e => !e.client_id || !e.category);
    
    return {
      totalFound: expenses.length,
      potentialIssues: issues,
      allRecords: expenses
    };
  } catch (err) {
    console.error('Restoration analysis failed:', err);
    throw err;
  }
}

export async function processExpenseRestoration(expenseIds) {
  if (!expenseIds || expenseIds.length === 0) return { successCount: 0, errors: [] };

  let successCount = 0;
  const errors = [];

  for (const id of expenseIds) {
    try {
      const { error } = await supabase
        .from('expenses')
        .update({ updated_at: new Date().toISOString() })
        .eq('id', id);

      if (error) throw error;
      successCount++;
    } catch (err) {
      errors.push({ id, message: err.message });
    }
  }

  return { successCount, errors };
}
