<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use Spatie\Permission\Models\Role;

class CreateAdminUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create:admin {email} {password} {--name=Administrator}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create an admin user with Super Admin role';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $email = $this->argument('email');
        $password = $this->argument('password');
        $name = $this->option('name');

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

        // Create user
        $user = User::create([
            'name' => $name,
            'email' => $email,
            'password' => bcrypt($password),
            'email_verified_at' => now(),
        ]);

        // Assign Super Admin role
        $superAdminRole = Role::firstWhere('name', 'Super Admin');
        if ($superAdminRole) {
            $user->assignRole($superAdminRole);
            $this->info("Admin user created successfully with Super Admin role!");
        } else {
            $this->warning("User created but Super Admin role not found. Run permission seeder first.");
        }

        $this->table(['Name', 'Email', 'Role'], [
            [$user->name, $user->email, $superAdminRole ? 'Super Admin' : 'No Role']
        ]);

        return Command::SUCCESS;
    }
}