# PowerShell script to set up the complete EasyStream database
# This script executes the comprehensive database schema

Write-Host "Setting up complete EasyStream database schema..." -ForegroundColor Green

# Check if Docker is running
try {
    docker ps | Out-Null
    if ($LASTEXITCODE -ne 0) {
        Write-Host "Error: Docker is not running or not accessible" -ForegroundColor Red
        exit 1
    }
} catch {
    Write-Host "Error: Docker command not found. Please install Docker first." -ForegroundColor Red
    exit 1
}

# Check if the database container is running
$containerStatus = docker ps --filter "name=vs-db" --format "{{.Status}}"
if (-not $containerStatus) {
    Write-Host "Error: Database container 'vs-db' is not running" -ForegroundColor Red
    Write-Host "Please start the Docker containers first with: docker-compose up -d" -ForegroundColor Yellow
    exit 1
}

Write-Host "Database container status: $containerStatus" -ForegroundColor Cyan

# Wait for database to be ready
Write-Host "Checking database connectivity..." -ForegroundColor Yellow
$maxAttempts = 30
$attempt = 0

do {
    $attempt++
    Write-Host "Attempt $attempt/$maxAttempts - Testing database connection..." -ForegroundColor Gray
    
    $result = docker exec vs-db mysqladmin ping -h 127.0.0.1 -u root -proot --silent 2>$null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Database is ready!" -ForegroundColor Green
        break
    }
    
    if ($attempt -eq $maxAttempts) {
        Write-Host "Error: Database is not responding after $maxAttempts attempts" -ForegroundColor Red
        exit 1
    }
    
    Start-Sleep -Seconds 2
} while ($attempt -lt $maxAttempts)

# Execute the complete database schema
Write-Host "Executing complete EasyStream database schema..." -ForegroundColor Yellow

try {
    # Copy the SQL file to the container
    docker cp "deploy/create_db.sql" vs-db:/tmp/complete_schema.sql
    if ($LASTEXITCODE -ne 0) {
        Write-Host "Error: Failed to copy SQL file to container" -ForegroundColor Red
        exit 1
    }
    
    # Execute the SQL file
    $output = docker exec vs-db mysql -u root -proot easystream -e "source /tmp/complete_schema.sql" 2>&1
    if ($LASTEXITCODE -ne 0) {
        Write-Host "Error executing SQL script:" -ForegroundColor Red
        Write-Host $output -ForegroundColor Red
        exit 1
    }
    
    # Clean up the temporary file
    docker exec vs-db rm /tmp/complete_schema.sql
    
    Write-Host "Success! Complete EasyStream database schema has been applied." -ForegroundColor Green
    
} catch {
    Write-Host "Error: Failed to execute SQL script - $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# Verify key tables were created
Write-Host "Verifying database setup..." -ForegroundColor Yellow

$keyTables = @(
    "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"
)

$allTablesExist = $true
$createdCount = 0

foreach ($table in $keyTables) {
    $tableExists = docker exec vs-db mysql -u root -proot easystream -e "SHOW TABLES LIKE '$table';" --silent
    if ($tableExists -match $table) {
        Write-Host "✓ Table '$table' ready" -ForegroundColor Green
        $createdCount++
    } else {
        Write-Host "✗ Table '$table' missing" -ForegroundColor Red
        $allTablesExist = $false
    }
}

if ($allTablesExist) {
    Write-Host "`n🎉 SUCCESS! Complete EasyStream database is ready!" -ForegroundColor Green
    Write-Host "📊 Created/verified $createdCount essential tables" -ForegroundColor Cyan
    Write-Host "🚀 Platform features now available:" -ForegroundColor Cyan
    Write-Host "   • User management with RBAC" -ForegroundColor White
    Write-Host "   • Video processing and analytics" -ForegroundColor White
    Write-Host "   • Live streaming with SRS" -ForegroundColor White
    Write-Host "   • API management and logging" -ForegroundColor White
    Write-Host "   • Token monetization system" -ForegroundColor White
    Write-Host "   • Complete branding customization" -ForegroundColor White
    Write-Host "   • Advanced analytics and metrics" -ForegroundColor White
} else {
    Write-Host "`nSome tables were not created successfully. Please check the error messages above." -ForegroundColor Red
    exit 1
}

Write-Host "`n✅ EasyStream is production-ready! All database tables are in place." -ForegroundColor Green