#!/usr/bin/env fish

echo "🔧 Consolidating image fields..."

# Function to run SQL commands
function run_sql
    sudo -u postgres psql -d church_db -c "$argv[1]"
end

# SAFETY: Create backups first
echo "🛡️  Creating backups..."
run_sql "CREATE TABLE pending_events_backup AS SELECT * FROM pending_events;"
run_sql "CREATE TABLE events_backup AS SELECT * FROM events;"

echo "📊 Checking current data before migration..."
run_sql "SELECT COUNT(*) as total_pending FROM pending_events;"
run_sql "SELECT COUNT(*) as total_events FROM events;"

echo "🔍 Showing sample data structure..."
run_sql "SELECT id, image, image_path FROM pending_events LIMIT 3;"
run_sql "SELECT id, image, image_path FROM events LIMIT 3;"

echo "📋 Records that will be affected by consolidation..."
run_sql "SELECT COUNT(*) as pending_needs_copy FROM pending_events WHERE image IS NULL AND image_path IS NOT NULL;"
run_sql "SELECT COUNT(*) as events_needs_copy FROM events WHERE image IS NULL AND image_path IS NOT NULL;"

echo "⚠️  SAFETY CHECK: Review the above data. Press ENTER to continue or Ctrl+C to abort..."
read

echo "📝 Copying image_path data to image column..."
run_sql "UPDATE pending_events SET image = image_path WHERE image IS NULL AND image_path IS NOT NULL;"
run_sql "UPDATE events SET image = image_path WHERE image IS NULL AND image_path IS NOT NULL;"

echo "✅ Verifying consolidation..."
run_sql "SELECT COUNT(*) as pending_with_image FROM pending_events WHERE image IS NOT NULL;"
run_sql "SELECT COUNT(*) as events_with_image FROM events WHERE image IS NOT NULL;"

echo "🔍 Sample data after consolidation..."
run_sql "SELECT id, image, image_path FROM pending_events LIMIT 3;"

echo "⚠️  Ready to drop image_path columns. Press ENTER to continue or Ctrl+C to abort..."
read

echo "🗑️  Dropping image_path columns..."
run_sql "ALTER TABLE pending_events DROP COLUMN image_path;"
run_sql "ALTER TABLE events DROP COLUMN image_path;"

echo "🎉 Migration complete!"
echo "📋 Backup tables created: pending_events_backup, events_backup"
echo "💡 To rollback: DROP the current tables and rename backups back"
