require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');
const sb = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

(async () => {
  console.log('\n🗑️  CLEANING UP NON-STRATEGIC TASKS...\n');
  
  const toDelete = [
    'lead_gen', 'content', 'social_media', 'writing', 'feedback', 
    'research', 'data', 'translation', 'local', 'survey', 'other', 
    'image', 'audio', 'verification', 'social', 'micro'
  ];

  let total = 0;
  for (const cat of toDelete) {
    try {
      const { count } = await sb
        .from('tasks')
        .delete()
        .eq('category', cat)
        .select('*', { count: 'exact', head: true });
      
      if (count > 0) {
        console.log(`✅ Deleted ${count} from ${cat}`);
        total += count;
      }
    } catch (e) {
      console.log(`⚠️  Error deleting ${cat}: ${e.message}`);
    }
  }

  // Delete duplicate Product Hunt tasks
  try {
    const { data: ph } = await sb
      .from('tasks')
      .select('id')
      .eq('category', 'product_hunt')
      .order('budget_vae', { ascending: false });
    
    if (ph && ph.length > 1) {
      const idsToDelete = ph.slice(1).map(x => x.id);
      const { count: delCount } = await sb
        .from('tasks')
        .delete()
        .in('id', idsToDelete)
        .select('*', { count: 'exact', head: true });
      
      console.log(`✅ Deleted ${delCount} duplicate Product Hunt tasks (kept 1)`);
      total += delCount;
    }
  } catch (e) {
    console.log(`⚠️  Error: ${e.message}`);
  }

  // Get final count
  try {
    const { count: remaining } = await sb
      .from('tasks')
      .select('id', { count: 'exact', head: true });
    
    console.log(`\n✨ DONE! Deleted ${total} tasks. ${remaining} tasks remaining.\n`);
  } catch (e) {
    console.log(`Error: ${e.message}`);
  }
})();
