<?php
require __DIR__ . '/vendor/autoload.php';
$app = require_once __DIR__ . '/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

use App\Models\Ad;
use App\Models\AdPackage;
use App\Models\AdPackagePurchase;
use Illuminate\Support\Facades\DB;

try {
    // 1. Ensure we have a test package 'Super Boost'
    $package = AdPackage::firstOrCreate(
        ['slug' => 'super-boost'],
        [
            'name' => 'Super Boost',
            'type' => 'boost',
            'is_active' => true,
            'features' => [],
            'description' => 'Super Boost Package',
            'algorithm_params' => ['boost' => 85]
        ]
    );
    
    // Update boost if already exists to ensure we know the value
    $package->algorithm_params = ['boost' => 85];
    $package->save();

    echo "Package: " . $package->name . " (Boost: " . $package->algorithm_params['boost'] . ")\n";

    // 2. Ensure we have a pricing tier
    $tier = App\Models\PackagePricingTier::firstOrCreate(
        ['package_id' => $package->id, 'validity_days' => 7],
        [
            'base_price' => 10,
            'final_price' => 10,
            'is_active' => true
        ]
    );

    // 3. Get a test ad
    $ad = Ad::first();
    if (!$ad) {
        echo "No ads found.\n";
        exit;
    }
    echo "Testing Ad: " . $ad->title . " (ID: " . $ad->id . ")\n";

    // 4. Check score BEFORE package
    $scoreBefore = Ad::where('ads.id', $ad->id)->orderByInterestAndLocation()->first()->relevance_score;
    echo "Score BEFORE Package: " . $scoreBefore . "\n";

    // 5. Assign package to ad
    AdPackagePurchase::where('ad_id', $ad->id)->delete(); // Clean up
    AdPackagePurchase::create([
        'user_id' => $ad->user_id,
        'package_id' => $package->id,
        'pricing_tier_id' => $tier->id,
        'ad_id' => $ad->id,
        'category_id' => $ad->category_id,
        'status' => 'active',
        'location_country' => 'India',
        'location_scope' => 'country',
        'total_paid' => 10.00,
        'currency' => 'INR',
        'usage_limit' => 1,
        'usage_count' => 0,
        'features_granted' => [],
        'expires_at' => now()->addDays(7),
        'purchased_at' => now()
    ]);

    // 5. Check score AFTER package
    $scoreAfter = Ad::where('ads.id', $ad->id)->orderByInterestAndLocation()->first()->relevance_score;
    echo "Score AFTER Package: " . $scoreAfter . "\n";

    $diff = $scoreAfter - $scoreBefore;
    echo "Difference: " . $diff . " (Expected: " . ($package->algorithm_params['boost'] * 10) . ")\n";

    if (abs($diff - ($package->algorithm_params['boost'] * 10)) < 0.01) {
        echo "✅ SUCCESS: Package boost applied correctly!\n";
    } else {
        echo "❌ FAILURE: Boost discrepancy detected.\n";
    }

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