#!/bin/bash
# Bash script to set up the complete EasyStream database
# This script executes the comprehensive database schema

echo "Setting up complete EasyStream database schema..."

# Check if Docker is running
if ! docker ps >/dev/null 2>&1; then
    echo "Error: Docker is not running or not accessible"
    exit 1
fi

# Check if the database container is running
if ! docker ps --filter "name=vs-db" --format "{{.Names}}" | grep -q "vs-db"; then
    echo "Error: Database container 'vs-db' is not running"
    echo "Please start the Docker containers first with: docker-compose up -d"
    exit 1
fi

echo "Database container is running"

# Wait for database to be ready
echo "Checking database connectivity..."
max_attempts=30
attempt=0

while [ $attempt -lt $max_attempts ]; do
    attempt=$((attempt + 1))
    echo "Attempt $attempt/$max_attempts - Testing database connection..."
    
    if docker exec vs-db mysqladmin ping -h 127.0.0.1 -u root -proot --silent >/dev/null 2>&1; then
        echo "Database is ready!"
        break
    fi
    
    if [ $attempt -eq $max_attempts ]; then
        echo "Error: Database is not responding after $max_attempts attempts"
        exit 1
    fi
    
    sleep 2
done

# Execute the complete database schema
echo "Executing complete EasyStream database schema..."

# Copy the SQL file to the container
if ! docker cp "deploy/create_db.sql" vs-db:/tmp/complete_schema.sql; then
    echo "Error: Failed to copy SQL file to container"
    exit 1
fi

# Execute the SQL file
if ! docker exec vs-db mysql -u root -proot easystream -e "source /tmp/complete_schema.sql"; then
    echo "Error: Failed to execute SQL script"
    exit 1
fi

# Clean up the temporary file
docker exec vs-db rm /tmp/complete_schema.sql

echo "Success! Complete EasyStream database schema has been applied."

# Verify key tables were created
echo "Verifying database setup..."

tables=("db_accountuser" "db_videofiles" "db_roles" "db_user_roles" "db_role_permissions" "db_live_streams" "db_stream_viewers" "db_api_keys" "db_api_logs" "db_video_analytics" "db_platform_metrics" "token_transactions" "token_purchases" "token_donations" "db_branding_settings" "db_branding_images")

all_tables_exist=true
created_count=0

for table in "${tables[@]}"; do
    if docker exec vs-db mysql -u root -proot easystream -e "SHOW TABLES LIKE '$table';" --silent | grep -q "$table"; then
        echo "✓ Table '$table' ready"
        created_count=$((created_count + 1))
    else
        echo "✗ Table '$table' missing"
        all_tables_exist=false
    fi
done

if [ "$all_tables_exist" = true ]; then
    echo ""
    echo "🎉 SUCCESS! Complete EasyStream database is ready!"
    echo "📊 Created/verified $created_count essential tables"
    echo "🚀 Platform features now available:"
    echo "   • User management with RBAC"
    echo "   • Video processing and analytics"
    echo "   • Live streaming with SRS"
    echo "   • API management and logging"
    echo "   • Token monetization system"
    echo "   • Complete branding customization"
    echo "   • Advanced analytics and metrics"
else
    echo ""
    echo "Some tables were not created successfully. Please check the error messages above."
    exit 1
fi

echo ""
echo "✅ EasyStream is production-ready! All database tables are in place."