<?php

use App\Http\Controllers\Admin\AlgorithmController;
use App\Models\AlgorithmConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

echo "--- TESTING VIP SETTINGS UPDATE ---\n";

// 1. Snapshot Init
$config = AlgorithmConfig::getDefault();
$initialVip = $config->vip_settings['vip_tiers'] ?? [];
echo "Initial Platinum Boost: " . ($initialVip['platinum_boost'] ?? 'N/A') . "\n";

// 2. Simulate Request
// User says "I increased %". Let's try to set Platinum to 99.
$newData = [
    'weights' => $config->weights, // Keep existing weights to pass validation
    'vip_tiers' => [
        'platinum_boost' => 99,
        'gold_boost' => 88,
        'silver_boost' => 77,
        'free_boost' => 66
    ],
    'priority_ranking' => true
];

$request = new Request($newData);

// Manually instantiate controller and call updateConfig logic
// Since we can't easily call the private methods, we'll try to replicate the logic or instantiate the controller if methods are public?
// updateConfig is public.
$controller = new AlgorithmController();

try {
    // We need to act as if we are the route. validate() on $request might fail if not in route context?
    // Controller uses $request->validate(). In Tinker/Console, independent Request might not work with that helper seamlessly if not bound to container.
    // Let's manually call the Validator logic to see if it passes.
    
    $validator = Validator::make($newData, [
        'weights' => 'required|array',
        'weights.location_relevance' => 'numeric|min:0|max:100',
        'vip_tiers' => 'array',
        'vip_tiers.platinum_boost' => 'numeric|min:0|max:100',
    ]);
    
    if ($validator->fails()) {
        echo "Validation Failed: " . implode(', ', $validator->errors()->all()) . "\n";
    } else {
        echo "Validation Passed.\n";
        // Call the endpoint (simulated)
        $response = $controller->updateConfig($request);
        echo "Controller Response: " . json_encode($response->getData()) . "\n";
    }

} catch (\Exception $e) {
    echo "Exception: " . $e->getMessage() . "\n";
}

// 3. Verify Persistence
$config->refresh();
$newVip = $config->vip_settings['vip_tiers'] ?? [];
echo "New Platinum Boost: " . ($newVip['platinum_boost'] ?? 'N/A') . "\n";

if (($newVip['platinum_boost'] ?? 0) == 99) {
    echo "SUCCESS: Settings Persisted.\n";
} else {
    echo "FAILURE: Settings Reset/Not Saved.\n";
}
