#!/bin/bash
# =====================================================
# Database Schema Validation Script
# Purpose: Apply all database fixes and verify alignment
# Date: January 3, 2026
# =====================================================

set -e  # Exit on error

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DB_NAME="skyartshop"
DB_USER="skyartapp"
DB_HOST="localhost"
export PGPASSWORD="SkyArt2025Pass"

echo "=================================="
echo "SkyArtShop Database Fix & Validation"
echo "=================================="
echo ""

# Check if PostgreSQL is running
echo "1. Checking PostgreSQL connection..."
if ! psql -U $DB_USER -d $DB_NAME -h $DB_HOST -c "SELECT 1;" > /dev/null 2>&1; then
    echo "❌ Cannot connect to PostgreSQL"
    echo "   Make sure PostgreSQL is running and credentials are correct"
    exit 1
fi
echo "✅ PostgreSQL connection successful"
echo ""

# Apply database analysis and fixes
echo "2. Applying database schema fixes..."
if psql -U $DB_USER -d $DB_NAME -h $DB_HOST -f "$SCRIPT_DIR/database-analysis-fixes.sql" > /dev/null 2>&1; then
    echo "✅ Database schema fixes applied"
else
    echo "⚠️  Some fixes may have failed (this is normal if they were already applied)"
fi
echo ""

# Verify tables exist
echo "3. Verifying core tables..."
TABLES=(
    "products"
    "product_images"
    "adminusers"
    "uploads"
    "media_folders"
    "blogposts"
    "portfolioprojects"
    "pages"
    "homepagesections"
    "team_members"
    "site_settings"
)

MISSING_TABLES=()
for table in "${TABLES[@]}"; do
    if psql -U $DB_USER -d $DB_NAME -h $DB_HOST -tAc "SELECT to_regclass('public.$table');" | grep -q "$table"; then
        echo "   ✅ $table"
    else
        echo "   ❌ $table (MISSING)"
        MISSING_TABLES+=("$table")
    fi
done
echo ""

if [ ${#MISSING_TABLES[@]} -gt 0 ]; then
    echo "⚠️  Missing tables: ${MISSING_TABLES[*]}"
    echo "   Please create these tables manually"
else
    echo "✅ All core tables exist"
fi
echo ""

# Verify indexes
echo "4. Checking critical indexes..."
INDEXES=(
    "idx_products_isactive"
    "idx_products_slug"
    "idx_product_images_product_id"
    "idx_blogposts_slug"
    "idx_pages_slug"
    "idx_uploads_folder_id"
)

MISSING_INDEXES=()
for index in "${INDEXES[@]}"; do
    if psql -U $DB_USER -d $DB_NAME -h $DB_HOST -tAc "SELECT to_regclass('public.$index');" | grep -q "$index"; then
        echo "   ✅ $index"
    else
        echo "   ⚠️  $index (missing or pending)"
        MISSING_INDEXES+=("$index")
    fi
done
echo ""

if [ ${#MISSING_INDEXES[@]} -gt 0 ]; then
    echo "⚠️  Some indexes are missing: ${MISSING_INDEXES[*]}"
else
    echo "✅ All critical indexes exist"
fi
echo ""

# Verify foreign keys
echo "5. Checking foreign key constraints..."
FK_COUNT=$(psql -U $DB_USER -d $DB_NAME -h $DB_HOST -tAc "
    SELECT COUNT(*) 
    FROM information_schema.table_constraints 
    WHERE constraint_type = 'FOREIGN KEY' 
        AND table_schema = 'public';
")
echo "   Found $FK_COUNT foreign key constraints"
echo ""

# Show table row counts
echo "6. Table row counts:"
psql -U $DB_USER -d $DB_NAME -h $DB_HOST -c "
    SELECT 'products' as table_name, COUNT(*) as rows FROM products
    UNION ALL
    SELECT 'product_images', COUNT(*) FROM product_images
    UNION ALL
    SELECT 'blogposts', COUNT(*) FROM blogposts
    UNION ALL
    SELECT 'portfolioprojects', COUNT(*) FROM portfolioprojects
    UNION ALL
    SELECT 'pages', COUNT(*) FROM pages
    UNION ALL
    SELECT 'uploads', COUNT(*) FROM uploads
    UNION ALL
    SELECT 'media_folders', COUNT(*) FROM media_folders
    UNION ALL
    SELECT 'adminusers', COUNT(*) FROM adminusers
    ORDER BY table_name;
" 2>/dev/null || echo "   Unable to query row counts"
echo ""

# Check for missing columns
echo "7. Validating critical columns..."
COLUMN_CHECKS=(
    "products:slug"
    "products:shortdescription"
    "products:isfeatured"
    "product_images:color_variant"
    "product_images:variant_price"
    "uploads:folder_id"
    "pages:ispublished"
)

MISSING_COLUMNS=()
for check in "${COLUMN_CHECKS[@]}"; do
    table="${check%:*}"
    column="${check#*:}"
    
    if psql -U $DB_USER -d $DB_NAME -h $DB_HOST -tAc "
        SELECT COUNT(*) 
        FROM information_schema.columns 
        WHERE table_name = '$table' 
            AND column_name = '$column';
    " | grep -q "1"; then
        echo "   ✅ $table.$column"
    else
        echo "   ❌ $table.$column (MISSING)"
        MISSING_COLUMNS+=("$table.$column")
    fi
done
echo ""

if [ ${#MISSING_COLUMNS[@]} -gt 0 ]; then
    echo "❌ Missing columns: ${MISSING_COLUMNS[*]}"
else
    echo "✅ All critical columns exist"
fi
echo ""

# Run ANALYZE for query optimization
echo "8. Running ANALYZE to update statistics..."
psql -U $DB_USER -d $DB_NAME -h $DB_HOST -c "ANALYZE;" > /dev/null 2>&1
echo "✅ Database statistics updated"
echo ""

# Summary
echo "=================================="
echo "VALIDATION SUMMARY"
echo "=================================="

TOTAL_ISSUES=0
if [ ${#MISSING_TABLES[@]} -gt 0 ]; then
    echo "❌ Missing tables: ${#MISSING_TABLES[@]}"
    TOTAL_ISSUES=$((TOTAL_ISSUES + ${#MISSING_TABLES[@]}))
fi

if [ ${#MISSING_INDEXES[@]} -gt 0 ]; then
    echo "⚠️  Missing indexes: ${#MISSING_INDEXES[@]}"
fi

if [ ${#MISSING_COLUMNS[@]} -gt 0 ]; then
    echo "❌ Missing columns: ${#MISSING_COLUMNS[@]}"
    TOTAL_ISSUES=$((TOTAL_ISSUES + ${#MISSING_COLUMNS[@]}))
fi

echo ""
if [ $TOTAL_ISSUES -eq 0 ]; then
    echo "✅ Database schema is healthy!"
    echo ""
    echo "Next steps:"
    echo "1. Review query optimization: query-optimization-analysis.sql"
    echo "2. Update Prisma schema: backend/prisma/schema-updated.prisma"
    echo "3. Restart backend server to apply changes"
else
    echo "⚠️  Found $TOTAL_ISSUES critical issues"
    echo ""
    echo "Please:"
    echo "1. Review the output above"
    echo "2. Run database-analysis-fixes.sql manually if needed"
    echo "3. Create any missing tables/columns"
fi
echo ""
echo "=================================="
