#!/bin/bash

# Chat Database Export Script
# This script exports the chat database schema and data for migration

set -e  # Exit on any error

echo "🚀 Starting chat database export..."

# Configuration - Update these values for your setup
DB_HOST="${CHAT_DB_HOST:-localhost}"
DB_PORT="${CHAT_DB_PORT:-5432}"
DB_NAME="${CHAT_DB_NAME:-rocketchat_converted}"
DB_USER="${CHAT_DB_USER:-rocketchat_user}"

# Check if database connection info is available
if [ -z "$CHAT_DB_PASSWORD" ]; then
    echo "⚠️  CHAT_DB_PASSWORD environment variable not set"
    echo "Please set it with: export CHAT_DB_PASSWORD='your_password'"
    exit 1
fi

echo "📊 Database: $DB_NAME on $DB_HOST:$DB_PORT"

# Create export directory
EXPORT_DIR="chat-migration-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$EXPORT_DIR"

echo "📁 Export directory: $EXPORT_DIR"

# Export database schema
echo "📋 Exporting database schema..."
PGPASSWORD="$CHAT_DB_PASSWORD" pg_dump \
    -h "$DB_HOST" \
    -p "$DB_PORT" \
    -U "$DB_USER" \
    -d "$DB_NAME" \
    --schema-only \
    --no-owner \
    --no-privileges \
    -f "$EXPORT_DIR/chat-schema.sql"

if [ $? -eq 0 ]; then
    echo "✅ Schema exported successfully"
else
    echo "❌ Schema export failed"
    exit 1
fi

# Export database data
echo "💾 Exporting database data..."
PGPASSWORD="$CHAT_DB_PASSWORD" pg_dump \
    -h "$DB_HOST" \
    -p "$DB_PORT" \
    -U "$DB_USER" \
    -d "$DB_NAME" \
    --data-only \
    --no-owner \
    --no-privileges \
    --disable-triggers \
    --column-inserts \
    -f "$EXPORT_DIR/chat-data.sql"

if [ $? -eq 0 ]; then
    echo "✅ Data exported successfully"
else
    echo "❌ Data export failed"
    exit 1
fi

# Export file uploads and avatars
echo "📎 Exporting chat files (uploads and avatars)..."
if [ -d "db-convert/db/files" ]; then
    cd db-convert/db
    tar -czf "../../$EXPORT_DIR/chat-files.tar.gz" files/
    cd ../..
    echo "✅ Files exported successfully"
else
    echo "⚠️  No files directory found at db-convert/db/files"
    echo "   This is normal if you have no file uploads"
    touch "$EXPORT_DIR/chat-files.tar.gz"
fi

# Get table statistics for verification
echo "📈 Generating export statistics..."
PGPASSWORD="$CHAT_DB_PASSWORD" psql \
    -h "$DB_HOST" \
    -p "$DB_PORT" \
    -U "$DB_USER" \
    -d "$DB_NAME" \
    -c "
    SELECT 
        schemaname,
        tablename, 
        n_tup_ins as inserted_rows,
        n_tup_upd as updated_rows,
        n_tup_del as deleted_rows,
        n_live_tup as live_rows,
        n_dead_tup as dead_rows
    FROM pg_stat_user_tables 
    ORDER BY n_live_tup DESC;
    " > "$EXPORT_DIR/table-stats.txt"

# Create export summary
cat > "$EXPORT_DIR/export-summary.txt" << EOF
Chat Database Export Summary
===========================

Export Date: $(date)
Database: $DB_NAME
Host: $DB_HOST:$DB_PORT
User: $DB_USER

Files Generated:
- chat-schema.sql: Database schema (tables, indexes, constraints)
- chat-data.sql: All table data
- chat-files.tar.gz: Uploaded files and avatars
- table-stats.txt: Database statistics
- export-summary.txt: This summary

Next Steps:
1. Transfer these files to your new server
2. Run create-new-database.sql on the new server first
3. Run import-chat-data.sh on the new server
4. Update your application configuration
5. Run verify-migration.js to validate the migration

Important Notes:
- Keep these files secure as they contain your chat data
- Ensure the new server has enough disk space
- Plan for application downtime during the migration
EOF

echo ""
echo "🎉 Export completed successfully!"
echo "📁 Files are in: $EXPORT_DIR/"
echo ""
echo "📋 Export Summary:"
ls -lh "$EXPORT_DIR/"
echo ""
echo "🚚 Next steps:"
echo "1. Transfer the $EXPORT_DIR/ directory to your new server"
echo "2. Run create-new-database.sql on the new server (update password first!)"
echo "3. Run import-chat-data.sh on the new server"
echo ""
echo "💡 To transfer files to new server:"
echo "   scp -r $EXPORT_DIR/ user@new-server:/tmp/"
