const { createClient } = require('@supabase/supabase-js');

const SUPABASE_URL = 'https://avxzzqudkqboesygfysr.supabase.co';
const SUPABASE_SERVICE_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImF2eHp6cXVka3Fib2VzeWdmeXNyIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc2NTg5NTM4NywiZXhwIjoyMDgxNDcxMzg3fQ.6LJGZulo8e8NTGv8tQMXNfFdH_zpzsihaWDIuBsH8Gk';
const CHECK_INTERVAL_MS = 5 * 60 * 1000;
const TIMEOUTS = { verification:15, content_moderation:15, data_labeling:60, social_media:60, testing_qa:60, translation:120, research:240, default:60 };

const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);

function getTimeout(category) {
  const key = (category||'').toLowerCase().replace(/[\s-]/g,'_');
  return TIMEOUTS[key] || TIMEOUTS.default;
}

async function runExpiry() {
  const now = new Date();
  console.log(`[expiry-cron] Running at ${now.toISOString()}`);
  try {
    // Step 1: Get active acceptances
    const { data: acceptances, error } = await supabase
      .from('task_acceptances')
      .select('id, task_id, worker_id, status, created_at')
      .in('status', ['accepted','claimed','in_progress']);

    if (error) { console.error('[expiry-cron] Fetch error:', error.message); return; }
    if (!acceptances || acceptances.length === 0) { console.log('[expiry-cron] Nothing to check.'); return; }

    console.log(`[expiry-cron] Checking ${acceptances.length} acceptance(s)...`);

    // Step 2: Get task categories separately
    const taskIds = [...new Set(acceptances.map(a => a.task_id))];
    const { data: tasks } = await supabase
      .from('tasks')
      .select('id, category, title')
      .in('id', taskIds);

    const taskMap = {};
    (tasks||[]).forEach(t => taskMap[t.id] = t);

    // Step 3: Find expired acceptances
    const expiredIds = [];
    const expiredTaskIds = new Set();

    for (const acc of acceptances) {
      const task = taskMap[acc.task_id] || {};
      const mins = getTimeout(task.category);
      const expiresAt = new Date(new Date(acc.created_at).getTime() + mins * 60000);
      if (now >= expiresAt) {
        expiredIds.push(acc.id);
        expiredTaskIds.add(acc.task_id);
        console.log(`[expiry-cron] Expiring acceptance for "${task.title||acc.task_id}" (${mins}min timeout)`);
      }
    }

    if (expiredIds.length === 0) { console.log('[expiry-cron] No expired acceptances.'); return; }

    // Step 4: Mark acceptances expired
    await supabase.from('task_acceptances')
      .update({ status:'expired', updated_at: now.toISOString() })
      .in('id', expiredIds);

    // Step 5: Reset affected tasks to open
    for (const taskId of expiredTaskIds) {
      const { count } = await supabase
        .from('task_acceptances')
        .select('id', { count:'exact', head:true })
        .eq('task_id', taskId)
        .in('status', ['accepted','claimed','in_progress']);

      if (count === 0) {
        await supabase.from('tasks')
          .update({ status:'open', current_workers:0, updated_at: now.toISOString() })
          .eq('id', taskId)
          .in('status', ['full','claimed']);
        console.log(`[expiry-cron] ✅ Task ${taskId} reset to OPEN`);
      }
    }

    console.log(`[expiry-cron] ✅ Done. ${expiredIds.length} expired, ${expiredTaskIds.size} tasks reset.`);
  } catch(err) {
    console.error('[expiry-cron] Error:', err.message);
  }
}

console.log('[expiry-cron] Starting... timeouts:', TIMEOUTS);
runExpiry();
setInterval(runExpiry, CHECK_INTERVAL_MS);
