#!/bin/bash

# Chat Database Import Script
# This script imports the chat database schema and data on the new server

set -e  # Exit on any error

echo "🚀 Starting chat database import..."

# Configuration - Update these values for your new server
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

# Find the migration directory
MIGRATION_DIR=""
if [ -d "/tmp" ]; then
    MIGRATION_DIR=$(find /tmp -maxdepth 1 -name "chat-migration-*" -type d | head -1)
fi

if [ -z "$MIGRATION_DIR" ]; then
    echo "❌ No migration directory found in /tmp/"
    echo "Please specify the migration directory:"
    read -p "Enter full path to migration directory: " MIGRATION_DIR
fi

if [ ! -d "$MIGRATION_DIR" ]; then
    echo "❌ Migration directory not found: $MIGRATION_DIR"
    exit 1
fi

echo "📁 Using migration directory: $MIGRATION_DIR"
echo "📊 Target database: $DB_NAME on $DB_HOST:$DB_PORT"

# Verify required files exist
REQUIRED_FILES=("chat-schema.sql" "chat-data.sql" "chat-files.tar.gz")
for file in "${REQUIRED_FILES[@]}"; do
    if [ ! -f "$MIGRATION_DIR/$file" ]; then
        echo "❌ Required file not found: $MIGRATION_DIR/$file"
        exit 1
    fi
done

echo "✅ All required files found"

# Test database connection
echo "🔗 Testing database connection..."
PGPASSWORD="$CHAT_DB_PASSWORD" psql \
    -h "$DB_HOST" \
    -p "$DB_PORT" \
    -U "$DB_USER" \
    -d "$DB_NAME" \
    -c "SELECT version();" > /dev/null

if [ $? -eq 0 ]; then
    echo "✅ Database connection successful"
else
    echo "❌ Database connection failed"
    echo "Please ensure:"
    echo "  1. PostgreSQL is running"
    echo "  2. Database '$DB_NAME' exists"
    echo "  3. User '$DB_USER' has access"
    echo "  4. Password is correct"
    exit 1
fi

# Import database schema
echo "📋 Importing database schema..."
PGPASSWORD="$CHAT_DB_PASSWORD" psql \
    -h "$DB_HOST" \
    -p "$DB_PORT" \
    -U "$DB_USER" \
    -d "$DB_NAME" \
    -f "$MIGRATION_DIR/chat-schema.sql"

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

# Import database data
echo "💾 Importing database data..."
echo "   This may take a while depending on data size..."

PGPASSWORD="$CHAT_DB_PASSWORD" psql \
    -h "$DB_HOST" \
    -p "$DB_PORT" \
    -U "$DB_USER" \
    -d "$DB_NAME" \
    -f "$MIGRATION_DIR/chat-data.sql"

if [ $? -eq 0 ]; then
    echo "✅ Data imported successfully"
else
    echo "❌ Data import failed"
    echo "Check the error messages above for details"
    exit 1
fi

# Create files directory and import files
echo "📎 Setting up files directory..."
mkdir -p "db-convert/db"

if [ -s "$MIGRATION_DIR/chat-files.tar.gz" ]; then
    echo "📂 Extracting chat files..."
    cd db-convert/db
    tar -xzf "$MIGRATION_DIR/chat-files.tar.gz"
    cd ../..
    
    # Set proper permissions
    if [ -d "db-convert/db/files" ]; then
        chmod -R 755 db-convert/db/files
        echo "✅ Files imported and permissions set"
    else
        echo "⚠️  Files directory not created properly"
    fi
else
    echo "ℹ️  No files to import (empty archive)"
    mkdir -p "db-convert/db/files/uploads"
    mkdir -p "db-convert/db/files/avatars"
fi

# Get final table statistics
echo "📈 Generating import statistics..."
PGPASSWORD="$CHAT_DB_PASSWORD" psql \
    -h "$DB_HOST" \
    -p "$DB_PORT" \
    -U "$DB_USER" \
    -d "$DB_NAME" \
    -c "
    SELECT 
        tablename,
        n_live_tup as row_count
    FROM pg_stat_user_tables 
    WHERE schemaname = 'public'
    ORDER BY n_live_tup DESC;
    "

# Create import summary
echo ""
echo "🎉 Import completed successfully!"
echo ""
echo "📋 Import Summary:"
echo "  Database: $DB_NAME"
echo "  Host: $DB_HOST:$DB_PORT"
echo "  Files location: $(pwd)/db-convert/db/files/"
echo ""
echo "🔍 Next steps:"
echo "1. Update your application configuration to use this database"
echo "2. Run verify-migration.js to validate the migration"
echo "3. Test your application thoroughly"
echo "4. Update DNS/load balancer to point to new server"
echo ""
echo "⚠️  Important:"
echo "- Keep the original data as backup until migration is fully validated"
echo "- Monitor the application closely after switching"
echo "- Have a rollback plan ready"
