<?php

use App\Models\AdPackage;
use App\Models\PackagePricingTier;
use App\Models\AdPackagePurchase;
use App\Models\User;
use Illuminate\Support\Facades\DB;

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

// Get first user and first package
$user = User::first();
if (!$user) {
    die("No users found! Please register a user first.\n");
}

$package = AdPackage::active()->first();
if (!$package) {
    die("No active packages found! Please seed packages first.\n");
}

$tier = $package->pricingTiers()->first();

echo "Seeding purchase for User: {$user->name} (ID: {$user->id})\n";
echo "Package: {$package->name}\n";

$category = \App\Models\Category::first();
if (!$category) {
    die("No categories found! Please seed categories first.\n");
}

try {
    $purchase = AdPackagePurchase::create([
        'user_id' => $user->id,
        'package_id' => $package->id,
        'pricing_tier_id' => $tier ? $tier->id : null,
        'purchase_source' => 'buy_packages', // Correct enum value
        'total_paid' => $tier ? $tier->final_price : 0,
        'currency' => 'INR',
        'status' => 'active',
        'purchased_at' => now(),
        'expires_at' => now()->addDays($tier ? $tier->validity_days : 30),
        'features_granted' => $package->features,
        'usage_limit' => $package->features['post_limit'] ?? 1,
        'usage_count' => 0,
        // Location defaults
        'location_country' => 'India',
        'location_scope' => 'country',
        // Required Category
        'category_id' => $category->id
    ]);

    echo "✅ Purchase created successfully! ID: {$purchase->id}\n";
    echo "Status: {$purchase->status}\n";
    echo "Expires: {$purchase->expires_at}\n";
    
} catch (\Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
