#!/bin/bash

# Test Agent Creation
echo "Testing Agent Creation"
echo "====================="

# Generate a unique email for testing
TEST_EMAIL="test_agent_$(date +%s)@example.com"
TEST_NAME="Test Agent $(date +%s)"
TEST_REFERRAL_CODE="REF$(date +%s)"

# Create a user and agent using Tinker
echo "Creating test user and agent..."
TINKER_RESULT=$(php artisan tinker --execute="
try {
    \$user = App\\Models\\User::create([
        'name' => '$TEST_NAME',
        'email' => '$TEST_EMAIL',
        'password' => bcrypt('password'),
    ]);

    \$user->assignRole('agent');

    // Create agent directly with DB query to bypass model restrictions
    \$agent = DB::table('agents')->insertGetId([
        'user_id' => \$user->id,
        'tier' => 'FMO',
        'status' => 'approved',
        'experience' => '1-3',
        'commission_rate' => 50.00,
        'referral_code' => '$TEST_REFERRAL_CODE',
        'referral_token' => (string) Illuminate\\Support\\Str::uuid(),
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    echo 'SUCCESS: User and agent created successfully. Agent ID: ' . \$agent;
} catch (\\Exception \$e) {
    echo 'ERROR: ' . \$e->getMessage();
}
")

# Check if the agent was created successfully
if [[ $TINKER_RESULT == *"SUCCESS"* ]]; then
    echo "✅ Agent created successfully"
    echo "$TINKER_RESULT"

    # Verify the agent exists in the database
    DB_CHECK=$(php artisan tinker --execute="echo App\\Models\\User::where('email', '$TEST_EMAIL')->exists() ? 'exists' : 'not found';")

    if [[ $DB_CHECK == *"exists"* ]]; then
        echo "✅ Agent record verified in the database"
    else
        echo "❌ Agent record not found in the database (unexpected)"
    fi
else
    echo "❌ Agent creation failed"
    echo "$TINKER_RESULT"
fi

echo "Agent creation test completed!"
