require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');
const sb = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);
(async()=>{
  // Get all in_progress submissions with null content
  const {data:subs} = await sb.from('submissions')
    .select('id,task_id,worker_id')
    .eq('status','in_progress')
    .is('content',null);
  
  console.log('Ghost submissions to clear:',subs.length);
  
  for(const s of subs){
    // Abandon the submission
    await sb.from('submissions').update({status:'abandoned'}).eq('id',s.id);
    // Reopen the task
    await sb.from('tasks').update({status:'open', current_workers:0}).eq('id',s.task_id);
    console.log('Cleared sub',s.id.slice(0,8),'task reopened');
  }
  console.log('Done — all ghost submissions cleared, tasks reopened');
})();
