#!/bin/bash

# LOOPUMAN AUTOMATED TEST SUITE
# Tests all critical paths in 5 minutes

echo "🧪 LOOPUMAN TEST SUITE"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

TESTS_PASSED=0
TESTS_FAILED=0

# Test function
test_check() {
  if [ $1 -eq 0 ]; then
    echo -e "${GREEN}✅ $2${NC}"
    ((TESTS_PASSED++))
  else
    echo -e "${RED}❌ $2${NC}"
    ((TESTS_FAILED++))
  fi
}

echo "1️⃣  Testing Database Connection..."
psql "$SUPABASE_URL" -c "SELECT 1" >/dev/null 2>&1 || \
node -e "require('@supabase/supabase-js').createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY).from('app_users').select('count').single().then(() => process.exit(0)).catch(() => process.exit(1))"
test_check $? "Database connection"

echo ""
echo "2️⃣  Testing PM2 Services..."
pm2 list | grep -q "telegram-bot.*online"
test_check $? "Telegram bot running"

pm2 list | grep -q "whatsapp-bot.*online"
test_check $? "WhatsApp bot running"

pm2 list | grep -q "admin-bot.*online"
test_check $? "Admin bot running"

pm2 list | grep -q "scheduler.*online"
test_check $? "Scheduler running"

echo ""
echo "3️⃣  Testing Platform Wallet..."
node -e "
const { ethers } = require('ethers');
const provider = new ethers.JsonRpcProvider('https://forno.celo.org');
const wallet = new ethers.Wallet(process.env.TREASURY_PRIVATE_KEY, provider);
const cUSD = new ethers.Contract('0x765DE816845861e75A25fCA122bb6898B8B1282a', ['function balanceOf(address) view returns (uint256)'], provider);
cUSD.balanceOf(wallet.address).then(balance => {
  const usd = parseFloat(ethers.formatUnits(balance, 18));
  console.log('Balance: \$' + usd.toFixed(2));
  process.exit(usd > 0 ? 0 : 1);
}).catch(() => process.exit(1));
"
test_check $? "Platform wallet has cUSD"

echo ""
echo "4️⃣  Testing Website..."
curl -s -o /dev/null -w "%{http_code}" https://loopuman.com | grep -q "200\|301\|302"
test_check $? "Website accessible"

echo ""
echo "5️⃣  Testing Environment Variables..."
[ -n "$SUPABASE_URL" ]
test_check $? "SUPABASE_URL set"

[ -n "$TELEGRAM_BOT_TOKEN" ]
test_check $? "TELEGRAM_BOT_TOKEN set"

[ -n "$WA_ACCESS_TOKEN" ]
test_check $? "WA_ACCESS_TOKEN set"

[ -n "$TREASURY_PRIVATE_KEY" ]
test_check $? "TREASURY_PRIVATE_KEY set"

[ -n "$STRIPE_SECRET_KEY" ]
test_check $? "STRIPE_SECRET_KEY set"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📊 TEST RESULTS"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "${GREEN}✅ Passed: $TESTS_PASSED${NC}"
echo -e "${RED}❌ Failed: $TESTS_FAILED${NC}"
echo ""

if [ $TESTS_FAILED -eq 0 ]; then
  echo -e "${GREEN}🎉 ALL TESTS PASSED! Ready to launch!${NC}"
  exit 0
else
  echo -e "${RED}⚠️  Some tests failed. Fix before launching.${NC}"
  exit 1
fi
