const fs = require('fs');
const file = '/home/ubuntu/loopuman-backend/admin-bot.js';
let code = fs.readFileSync(file, 'utf8');

// 1. PATCH deposits_view to show usernames + pending + treasury
const oldDeposits = `  await edit(ctx, msg, Markup.inlineKeyboard([
    [Markup.button.callback('🔄 Refresh', 'deposits_view')],
    [Markup.button.callback('🔙 BACK', 'dashboard')],
  ]));
});`;

const newDeposits = `  // Show unmatched deposits
  const { count: unmatchedCount } = await supabase.from('unmatched_deposits')
    .select('*', { count: 'exact', head: true }).eq('status', 'pending').catch(() => ({ count: 0 }));
  if (unmatchedCount > 0) msg += \`\\n⚠️ <b>\${unmatchedCount} UNMATCHED DEPOSITS</b> — check treasury manually\\n\`;

  // Live treasury balance
  try {
    const treasury = await getTreasuryBalance();
    if (treasury) msg += \`\\n🏦 <b>Treasury:</b> \$\${treasury.totalUsd.toFixed(2)}\`;
  } catch(e) {}

  await edit(ctx, msg, Markup.inlineKeyboard([
    [Markup.button.callback('🔄 Refresh', 'deposits_view')],
    [Markup.button.callback('🚨 Unmatched', 'unmatched_deps')],
    [Markup.button.callback('🔙 BACK', 'dashboard')],
  ]));
});

// Unmatched deposits view
bot.action('unmatched_deps', async (ctx) => {
  await cb(ctx);
  const { data: unmatched } = await supabase.from('unmatched_deposits')
    .select('*').eq('status', 'pending').order('created_at', { ascending: false }).limit(10);
  let msg = '⚠️ <b>UNMATCHED DEPOSITS</b>\\n━━━━━━━━━━━━━━━━━━━━\\n\\n';
  if (!unmatched?.length) {
    msg += '✅ No unmatched deposits';
  } else {
    for (const d of unmatched) {
      const date = new Date(d.created_at).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' });
      msg += \`💰 \$\${d.amount_usd || '?'} • \${d.tx_hash?.slice(0,10) || 'no hash'}... • \${date}\\n\`;
      msg += \`   From: \${d.from_address?.slice(0,12) || 'unknown'}...\\n\\n\`;
    }
  }
  await edit(ctx, msg, Markup.inlineKeyboard([
    [Markup.button.callback('🔄 Refresh', 'unmatched_deps')],
    [Markup.button.callback('🔙 BACK', 'deposits_view')],
  ]));
});

// 2. USER LOOKUP + CREDIT command
bot.action('user_lookup', async (ctx) => {
  await cb(ctx);
  await edit(ctx, '🔍 <b>USER LOOKUP</b>\\n\\nSend username, Telegram ID, or phone:', Markup.inlineKeyboard([[Markup.button.callback('🔙 BACK', 'menu')]]));
  userSearchState.set(ctx.from.id, { action: 'lookup' });
});

bot.action(/^credit_user_(.+)$/, async (ctx) => {
  await cb(ctx);
  const userId = ctx.match[1];
  await edit(ctx, '💳 <b>CREDIT USER</b>\\n\\nHow many VAE to add? Send a number:', Markup.inlineKeyboard([[Markup.button.callback('🔙 Cancel', 'menu')]]));
  userSearchState.set(ctx.from.id, { action: 'credit_amount', userId });
});

bot.action(/^approve_task_(.+)$/, async (ctx) => {
  await cb(ctx);
  const taskId = ctx.match[1];
  await supabase.from('tasks').update({ status: 'open', updated_at: new Date().toISOString() }).eq('id', taskId);
  await edit(ctx, '✅ <b>Task approved and now live!</b>', Markup.inlineKeyboard([[Markup.button.callback('🔙 BACK', 'menu')]]));
});

// 3. RECENT TASKS view
bot.action('recent_tasks', async (ctx) => {
  await cb(ctx);
  const { data: tasks } = await supabase.from('tasks')
    .select('id, title, status, budget, created_at, requester:requester_id(username, first_name)')
    .order('created_at', { ascending: false }).limit(10);
  let msg = '📋 <b>RECENT TASKS</b>\\n━━━━━━━━━━━━━━━━━━━━\\n\\n';
  for (const t of tasks || []) {
    const date = new Date(t.created_at).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' });
    const name = t.requester?.username || t.requester?.first_name || 'unknown';
    const statusIcon = { open: '🟢', active: '🔵', completed: '✅', rejected: '❌', expired: '⏰' }[t.status] || '⚪';
    msg += \`\${statusIcon} <b>\${t.title?.slice(0,35) || 'Untitled'}</b>\\n\`;
    msg += \`   Ⓥ\${t.budget} • @\${name} • \${date}\\n\`;
    if (t.status === 'rejected') {
      msg += \`   <a href="tg://btn/approve_task_\${t.id}">Approve?</a>\\n\`;
    }
    msg += '\\n';
  }
  await edit(ctx, msg, Markup.inlineKeyboard([
    [Markup.button.callback('🔄 Refresh', 'recent_tasks')],
    [Markup.button.callback('🔙 BACK', 'dashboard')],
  ]));
});`;

// 4. Add menu buttons for new features
const oldMenuButtons = `    [Markup.button.callback('📊 Dashboard', 'dashboard')],
    [Markup.button.callback('👥 Users', 'users'), Markup.button.callback('💰 Withdrawals', 'withdrawals')],`;

const newMenuButtons = `    [Markup.button.callback('📊 Dashboard', 'dashboard')],
    [Markup.button.callback('👥 Users', 'users'), Markup.button.callback('💰 Withdrawals', 'withdrawals')],
    [Markup.button.callback('🔍 User Lookup', 'user_lookup'), Markup.button.callback('📋 Recent Tasks', 'recent_tasks')],
    [Markup.button.callback('💳 Deposits', 'deposits_view')],`;

// Apply patches
let patched = 0;
if (code.includes(oldDeposits)) { code = code.replace(oldDeposits, newDeposits); patched++; console.log('✅ Deposits view patched'); }
else console.log('❌ Deposits pattern not found');

if (code.includes(oldMenuButtons)) { code = code.replace(oldMenuButtons, newMenuButtons); patched++; console.log('✅ Menu buttons patched'); }
else console.log('❌ Menu buttons pattern not found');

// Add userSearchState map near top if not exists
if (!code.includes('userSearchState')) {
  code = code.replace('const supabase = createClient', 'const userSearchState = new Map();\nconst supabase = createClient');
  patched++; console.log('✅ userSearchState added');
}

fs.writeFileSync(file, code);
console.log(\`\\n✅ \${patched} patches applied\`);
