<?php

require __DIR__.'/vendor/autoload.php';

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

echo "Creating a new SSO token for testing\n";
echo "====================================\n\n";

// Get user ID from command line or use default
$userId = $argv[1] ?? 24; // Default to user 24 (from the failed token test)

$user = \App\Models\User::find($userId);

if (!$user) {
    echo "❌ User with ID $userId not found!\n";
    echo "\nLet's list some users:\n";
    $users = \App\Models\User::where('status', 'active')->take(5)->get();
    foreach ($users as $u) {
        echo "  ID: {$u->id}, Email: {$u->email}, Name: {$u->name}\n";
    }
    exit(1);
}

echo "✓ Found user:\n";
echo "  ID: {$user->id}\n";
echo "  Name: {$user->name}\n";
echo "  Email: {$user->email}\n";
echo "  Status: {$user->status}\n\n";

if ($user->status !== 'active') {
    echo "❌ User is not active! Status: {$user->status}\n";
    exit(1);
}

// Delete old tokens for this user (optional - clean up)
echo "Deleting old tokens for this user...\n";
$deletedCount = $user->tokens()->delete();
echo "Deleted $deletedCount old token(s)\n\n";

// Create a new token
echo "Creating new token...\n";
$tokenExpiry = now()->addDays(30); // 30 days
$tokenResult = $user->createToken('sso-test-token', ['*'], $tokenExpiry);
$plainTextToken = $tokenResult->plainTextToken;

echo "\n✅ Token created successfully!\n\n";
echo "========================================\n";
echo "Token (copy this entire string):\n";
echo "========================================\n";
echo "$plainTextToken\n";
echo "========================================\n\n";

echo "Test URLs:\n";
echo "- ImmiGoPro: http://localhost:5178/login?sso_token=" . urlencode($plainTextToken) . "\n";
echo "- Payments: http://localhost:5179/login?sso_token=" . urlencode($plainTextToken) . "\n";
echo "- Public Client: http://localhost:5179/login?sso_token=" . urlencode($plainTextToken) . "\n\n";

echo "Token expires at: $tokenExpiry\n";
