const fs = require('fs');
let code = fs.readFileSync('seo-server.js', 'utf8');

// Remove ALL ilike on id - replace with fetch all and filter in JS
const oldQuery = `const { data: tasks, error } = await supabase
      .from('tasks')
      .select('id, title, category, budget, max_workers, status, created_at, description, expires_at')
      .filter('id::text', 'ilike', \`\${prefix}%\`)
      .limit(1);`;

const newQuery = `const { data: allTasks, error } = await supabase
      .from('tasks')
      .select('id, title, category, budget, max_workers, status, created_at, description, expires_at')
      .order('created_at', { ascending: false })
      .limit(500);
    const tasks = allTasks ? allTasks.filter(t => t.id.replace(/-/g,'').startsWith(prefix) || t.id.startsWith(prefix)) : [];`;

code = code.replace(oldQuery, newQuery);

// Fix the task variable reference after
code = code.replace(
  `if (error) throw error;
    const task = tasks?.[0];`,
  `if (error) throw error;
    const task = tasks[0];`
);

fs.writeFileSync('seo-server.js', code);
console.log('Done! Checking...');
console.log('Has newQuery:', code.includes('allTasks.filter'));
