#!/bin/bash
# Database Health Check Script
# Quick verification of database status

echo "🏥 SkyArtShop Database Health Check"
echo "====================================="
echo ""

# Check PostgreSQL is running
echo "1️⃣ PostgreSQL Status:"
if sudo systemctl is-active --quiet postgresql; then
    echo "   ✅ PostgreSQL is running"
else
    echo "   ❌ PostgreSQL is not running"
    exit 1
fi
echo ""

# Check backend server
echo "2️⃣ Backend Server:"
if pm2 list | grep -q "skyartshop-backend.*online"; then
    echo "   ✅ Backend server is online"
else
    echo "   ⚠️  Backend server status unknown"
fi
echo ""

# Test database connection
echo "3️⃣ Database Connection:"
if node -e "const {pool}=require('./config/database');pool.query('SELECT 1').then(()=>{console.log('   ✅ Connection successful');pool.end();process.exit(0);}).catch(e=>{console.log('   ❌ Connection failed:',e.message);pool.end();process.exit(1);});" 2>/dev/null; then
    true
else
    echo "   ❌ Cannot connect to database"
    exit 1
fi
echo ""

# Check row counts
echo "4️⃣ Data Status:"
node -e "const {query,pool}=require('./config/database');(async()=>{try{const r=await query('SELECT (SELECT COUNT(*) FROM products) as products, (SELECT COUNT(*) FROM portfolioprojects) as portfolio, (SELECT COUNT(*) FROM blogposts) as blog, (SELECT COUNT(*) FROM pages) as pages');const d=r.rows[0];console.log('   Products:',d.products);console.log('   Portfolio:',d.portfolio);console.log('   Blog:',d.blog);console.log('   Pages:',d.pages);}catch(e){console.log('   ❌',e.message);}finally{await pool.end();}})()" 2>/dev/null
echo ""

# Check indexes
echo "5️⃣ Database Indexes:"
node -e "const {query,pool}=require('./config/database');(async()=>{try{const r=await query(\"SELECT COUNT(*) as count FROM pg_indexes WHERE schemaname='public' AND tablename IN ('products','product_images','portfolioprojects','blogposts','pages')\");console.log('   Total indexes:',r.rows[0].count);}catch(e){console.log('   ❌',e.message);}finally{await pool.end();}})()" 2>/dev/null
echo ""

# Test API endpoints
echo "6️⃣ API Endpoints:"
if curl -s http://localhost:5000/api/products > /dev/null 2>&1; then
    echo "   ✅ /api/products"
else
    echo "   ❌ /api/products"
fi

if curl -s http://localhost:5000/api/portfolio/projects > /dev/null 2>&1; then
    echo "   ✅ /api/portfolio/projects"
else
    echo "   ❌ /api/portfolio/projects"
fi

if curl -s http://localhost:5000/api/categories > /dev/null 2>&1; then
    echo "   ✅ /api/categories"
else
    echo "   ❌ /api/categories"
fi
echo ""

# Cache performance
echo "7️⃣ Cache Performance:"
node -e "const {query,pool}=require('./config/database');(async()=>{try{const r=await query(\"SELECT CASE WHEN sum(heap_blks_hit)+sum(heap_blks_read)>0 THEN round(100.0*sum(heap_blks_hit)/(sum(heap_blks_hit)+sum(heap_blks_read)),2) ELSE 0 END as ratio FROM pg_statio_user_tables WHERE schemaname='public'\");const ratio=r.rows[0].ratio;const status=ratio>99?'✅':ratio>95?'⚠️':'❌';console.log('  ',status,'Cache hit ratio:',ratio+'%','(target: >99%)');}catch(e){console.log('   ❌',e.message);}finally{await pool.end();}})()" 2>/dev/null
echo ""

echo "✅ Health check complete!"
echo ""
echo "To see detailed analysis, run:"
echo "  node analyze-queries.js"
