<?php
/**
 * discipline_settings_test.php
 * 
 * Test funkcjonalności endpointu ustawień dyscyplin
 * 
 * Uruchomienie: php discipline_settings_test.php
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "🧪 Testing Discipline Settings Service\n";
echo "=====================================\n\n";

// ===== INCLUDE =====
require_once __DIR__ . '/../administration/includes/config.php';
require_once __DIR__ . '/../api/DisciplineSettingsModel.php';
require_once __DIR__ . '/../api/DisciplineSettingsService.php';

// ===== MOCK SESSION =====
$_SESSION = [
    'user_id' => 1,
    'role' => 'admin'
];

// ===== INICJALIZACJA =====
try {
    $model = new DisciplineSettingsModel($pdo);
    $service = new DisciplineSettingsService($model);
    echo "✅ Model i Service zainicjalizowane\n\n";
} catch (Exception $e) {
    echo "❌ Błąd inicjalizacji: " . $e->getMessage() . "\n";
    exit(1);
}

// ===== TEST 1: Pobierz defaults dla ping-ponga =====
echo "TEST 1: Pobierz defaults dla ping-ponga\n";
echo "----------------------------------------\n";
try {
    $settings = $service->getSettingsForAPI('ping-pong');
    echo json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    echo "✅ PASS\n\n";
} catch (Exception $e) {
    echo "❌ FAIL: " . $e->getMessage() . "\n\n";
}

// ===== TEST 1.5: Wyczyść i zainicjalizuj defaults w bazie =====
echo "TEST 1.5: Inicjalizuj defaults w bazie danych\n";
echo "---------------------------------------------\n";
try {
    // Wyczyść stare dane ping-pong aby móc testować od nowa
    $model->deleteSettings('ping-pong');
    
    // Teraz inicjalizuj defaults
    $model->initializeIfNotExists('ping-pong', 1);
    $check = $model->getSettings('ping-pong');
    if ($check && $check['settingsVersion'] == 1) {
        echo "✅ PASS - Defaults zainstalowane w v1\n\n";
    } else {
        echo "❌ FAIL - Defaults nie zainstalowane (v" . ($check['settingsVersion'] ?? 'null') . ")\n\n";
    }
} catch (Exception $e) {
    echo "❌ FAIL: " . $e->getMessage() . "\n\n";
}

// ===== TEST 2: Zaktualizuj ustawienia ping-ponga =====
echo "TEST 2: Zaktualizuj ustawienia ping-ponga (v1→v2)\n";
echo "-----------------------------------------------\n";
try {
    $input = [
        'rules' => [
            'pointsToWin' => 21,
            'setsToWin' => 3,
            'serveRotation' => 2,
            'specialRules' => 'Professional rules - deuce at 20:20'
        ],
        'customization' => [
            'tableColor' => '#000000',
            'ballColor' => '#ffffff'
        ]
    ];
    
    $updated = $service->validateAndUpdate('ping-pong', $input, 1);
    echo "Updated:\n";
    echo json_encode($updated, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    echo "✅ PASS - Wersja: " . $updated['settingsVersion'] . " (powinna być 2)\n\n";
} catch (Exception $e) {
    echo "❌ FAIL: " . $e->getMessage() . "\n\n";
}

// ===== TEST 3: Pobierz snapshot =====
echo "TEST 3: Pobierz snapshot dla meczu\n";
echo "-----------------------------------\n";
try {
    $result = $service->getMatchSnapshot('ping-pong');
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    echo "✅ PASS\n\n";
} catch (Exception $e) {
    echo "❌ FAIL: " . $e->getMessage() . "\n\n";
}

// ===== TEST 4: Walidacja błędnych danych =====
echo "TEST 4: Walidacja - pointsToWin < 1\n";
echo "-----------------------------------\n";
try {
    $input = [
        'rules' => [
            'pointsToWin' => 0,  // ❌ Błąd
            'setsToWin' => 3,
            'serveRotation' => 2
        ]
    ];
    
    $service->validateAndUpdate('ping-pong', $input, 1);
    echo "❌ FAIL - Powinna wyrzucić exception\n\n";
} catch (InvalidArgumentException $e) {
    echo "✅ PASS - Prawidłowo złapana walidacja:\n";
    echo "   " . $e->getMessage() . "\n\n";
}

// ===== TEST 5: Walidacja - liczby parzyste =====
echo "TEST 5: Walidacja - pointsToWin parzyste\n";
echo "----------------------------------------\n";
try {
    $input = [
        'rules' => [
            'pointsToWin' => 10,  // ❌ Parzyste (możliwy remis)
            'setsToWin' => 2,
            'serveRotation' => 2
        ]
    ];
    
    $service->validateAndUpdate('ping-pong', $input, 1);
    echo "❌ FAIL - Powinna wyrzucić exception\n\n";
} catch (InvalidArgumentException $e) {
    echo "✅ PASS - Prawidłowo złapana walidacja:\n";
    echo "   " . $e->getMessage() . "\n\n";
}

// ===== TEST 6: Rock-Paper-Scissors =====
echo "TEST 6: Ustawienia dla rock-paper-scissors\n";
echo "----------------------------------------\n";
try {
    $settings = $service->getSettingsForAPI('rock-paper-scissors');
    echo "Defaults:\n";
    echo json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    echo "✅ PASS\n\n";
} catch (Exception $e) {
    echo "❌ FAIL: " . $e->getMessage() . "\n\n";
}

// ===== TEST 7: Porównanie wersji =====
echo "TEST 7: Porównanie wersji\n";
echo "------------------------\n";
try {
    $old = [
        'pointsToWin' => 11,
        'setsToWin' => 3,
        'serveRotation' => 2,
        'specialRules' => 'Old rules',
        'customization' => ['color' => 'red']
    ];
    
    $new = [
        'pointsToWin' => 21,
        'setsToWin' => 3,
        'serveRotation' => 2,
        'specialRules' => 'New rules',
        'customization' => ['color' => 'blue']
    ];
    
    $diff = $service->compareVersions($old, $new);
    echo "Zmiany:\n";
    echo json_encode($diff, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    echo "✅ PASS\n\n";
} catch (Exception $e) {
    echo "❌ FAIL: " . $e->getMessage() . "\n\n";
}

// ===== TEST 8: Reset do defaults =====
echo "TEST 8: Reset do defaults\n";
echo "------------------------\n";
try {
    $reset = $service->resetToDefaults('ping-pong', 1);
    echo "Reset do defaults:\n";
    echo "Version: " . $reset['settingsVersion'] . "\n";
    echo "PointsToWin: " . $reset['rules']['pointsToWin'] . "\n";
    echo "✅ PASS\n\n";
} catch (Exception $e) {
    echo "❌ FAIL: " . $e->getMessage() . "\n\n";
}

// ===== TEST 9: Brakujące pola =====
echo "TEST 9: Walidacja - brakujące rules\n";
echo "-----------------------------------\n";
try {
    $input = [
        'customization' => ['color' => 'red']
        // ❌ Brak rules
    ];
    
    $service->validateAndUpdate('ping-pong', $input, 1);
    echo "❌ FAIL - Powinna wyrzucić exception\n\n";
} catch (InvalidArgumentException $e) {
    echo "✅ PASS - Prawidłowo złapana walidacja:\n";
    echo "   " . $e->getMessage() . "\n\n";
}

// ===== TEST 10: Nieznana dyscyplina =====
echo "TEST 10: Walidacja - nieznana dyscyplina\n";
echo "---------------------------------------\n";
try {
    $service->getSettingsForAPI('unknown-discipline');
    echo "❌ FAIL - Powinna wyrzucić exception\n\n";
} catch (InvalidArgumentException $e) {
    echo "✅ PASS - Prawidłowo złapana walidacja:\n";
    echo "   " . $e->getMessage() . "\n\n";
}

echo "=====================================\n";
echo "🎉 Testy ukończone (11 testów)\n";
?>
