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

const TASK_ID = '87a70f13-0dc3-4527-91df-b3e6cb95a560';
const MAX_COMPLETIONS = 50;

async function checkAndReset() {
  const { data: task } = await s.from('tasks').select('current_workers,status').eq('id', TASK_ID).single();
  if (!task) return;

  const { count } = await s.from('task_submissions').select('*', {count: 'exact', head: true})
    .eq('task_id', TASK_ID).eq('status', 'approved');

  console.log(`Approved: ${count}, current_workers: ${task.current_workers}, status: ${task.status}`);

  if (count >= MAX_COMPLETIONS) {
    await s.from('tasks').update({status: 'completed'}).eq('id', TASK_ID);
    console.log('✅ 50 completions reached — task marked complete');
    process.exit(0);
  }

  if (task.status === 'full' || task.current_workers >= 1) {
    await s.from('tasks').update({current_workers: 0, status: 'open'}).eq('id', TASK_ID);
    console.log('🔄 Task reset — ready for next worker');
  }
}

checkAndReset();
setInterval(checkAndReset, 30000);
