<?php
/**
 * Run Database Concurrency Optimizations
 * Execute the SQL optimization script
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';

echo "Starting database concurrency optimizations...\n";

$sqlFile = __DIR__ . '/database/optimize_concurrency.sql';

if (!file_exists($sqlFile)) {
    die("Error: SQL file not found at $sqlFile\n");
}

$sql = file_get_contents($sqlFile);

// Split by semicolon to get individual statements
$statements = array_filter(array_map('trim', explode(';', $sql)));

try {
    $pdo = db();
    
    foreach ($statements as $statement) {
        if (empty($statement) || str_starts_with($statement, '--') || str_starts_with($statement, '/*')) {
            continue;
        }
        
        // Skip commented lines and empty statements
        if (preg_match('/^(--|#)/', $statement)) {
            continue;
        }
        
        // Skip SET GLOBAL statements (require superuser privileges)
        if (str_starts_with(strtoupper($statement), 'SET GLOBAL')) {
            echo "Skipping SET GLOBAL statement (requires superuser)\n";
            continue;
        }
        
        try {
            echo "Executing: " . substr($statement, 0, 60) . "...\n";
            $pdo->exec($statement);
            echo "  ✓ Success\n";
        } catch (PDOException $e) {
            // Check if it's a duplicate index error
            if (str_contains($e->getMessage(), 'Duplicate key name')) {
                echo "  ⊘ Index already exists (skipping)\n";
            } else {
                echo "  ✗ Error: " . $e->getMessage() . "\n";
            }
        }
    }
    
    echo "\n✓ Database concurrency optimizations completed successfully!\n";
    
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage() . "\n");
}
