<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class CreateInitialAdmin extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'authentikate:create-admin 
                            {--email= : The email address for the admin user}
                            {--name= : The name for the admin user}
                            {--force : Force creation even if admin users already exist}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create the initial admin user for AuthentiKate';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // Check if admin users already exist (unless forced)
        if (!$this->option('force') && User::where('is_admin', true)->exists()) {
            $this->error('Admin users already exist! Use --force to create anyway.');
            return Command::SUCCESS;
        }

        // Get user input for email and name
        $email = $this->option('email') ?: $this->ask('Admin email address', 'admin@authentikate.local');
        $name = $this->option('name') ?: $this->ask('Admin name', 'Administrator');

        // Validate email format
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->error('Invalid email address format.');
            return Command::SUCCESS;
        }

        // Check if email already exists
        if (User::where('email', $email)->exists()) {
            $this->error("A user with email '{$email}' already exists.");
            return Command::SUCCESS;
        }

        // Generate a random password
        $password = $this->generateSecurePassword();

        // Create the admin user
        $user = User::create([
            'name' => $name,
            'email' => $email,
            'password' => Hash::make($password),
            'email_verified_at' => now(),
            'is_admin' => true,
        ]);

        // Display success message with login credentials
        $this->info('✅ Initial admin user created successfully!');
        $this->newLine();

        $this->line('🔐 <options=bold>Login Credentials:</options=bold>');
        $this->line("📧 Email:    <fg=yellow>{$email}</>");
        $this->line("🔑 Password: <fg=yellow>{$password}</>");
        $this->newLine();

        $this->warn('⚠️  Please log in and change your password immediately!');
        $this->info('💡 You can access the admin panel to manage users and applications.');

        return Command::SUCCESS;
    }

    /**
     * Generate a secure random password
     */
    private function generateSecurePassword(): string
    {
        // Generate a password with a mix of uppercase, lowercase, numbers, and symbols
        $length = 16;
        $lowercase = 'abcdefghijklmnopqrstuvwxyz';
        $uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $numbers = '0123456789';
        $symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';

        $password = '';

        // Ensure at least one character from each category
        $password .= $lowercase[random_int(0, strlen($lowercase) - 1)];
        $password .= $uppercase[random_int(0, strlen($uppercase) - 1)];
        $password .= $numbers[random_int(0, strlen($numbers) - 1)];
        $password .= $symbols[random_int(0, strlen($symbols) - 1)];

        // Fill the rest with random characters from all categories
        $allChars = $lowercase . $uppercase . $numbers . $symbols;
        for ($i = 4; $i < $length; $i++) {
            $password .= $allChars[random_int(0, strlen($allChars) - 1)];
        }

        // Shuffle the password to randomize the order
        return str_shuffle($password);
    }
}
