#!/bin/bash
# Bash script to add missing database tables to Docker container
# This script executes the combined SQL file in the MariaDB container

echo "Adding missing database tables to Docker container..."

# 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 SQL file
echo "Executing SQL script to add missing tables..."

# Copy the SQL file to the container
if ! docker cp "deploy/add_missing_tables.sql" vs-db:/tmp/add_missing_tables.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/add_missing_tables.sql"; then
    echo "Error: Failed to execute SQL script"
    exit 1
fi

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

echo "Success! All missing database tables have been added."

# Verify tables were created
echo "Verifying table creation..."

tables=("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")

all_tables_exist=true
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' created successfully"
    else
        echo "✗ Table '$table' was not created"
        all_tables_exist=false
    fi
done

if [ "$all_tables_exist" = true ]; then
    echo ""
    echo "All database tables have been successfully added to the Docker container!"
    echo "The EasyStream platform now has complete RBAC, Live Streaming, and Analytics functionality."
else
    echo ""
    echo "Some tables were not created successfully. Please check the error messages above."
    exit 1
fi

echo ""
echo "Database setup complete! You can now use all platform features."