<?php

namespace App\Console\Commands;

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

class CreateSuperAdmin extends Command
{
    protected $signature = 'numerix:super-admin {email} {password} {name=Super Admin}';
    protected $description = 'Create or reset the super admin account';

    public function handle(): int
    {
        // Ensure role exists
        Role::firstOrCreate(['name' => 'super_admin', 'guard_name' => 'sanctum']);

        $email    = $this->argument('email');
        $password = $this->argument('password');
        $name     = $this->argument('name');

        $user = User::updateOrCreate(
            ['email' => $email],
            [
                'name'      => $name,
                'password'  => Hash::make($password),
                'tenant_id' => null,
            ]
        );

        $user->syncRoles(['super_admin']);

        $this->info("Super admin created/updated: {$email}");
        return self::SUCCESS;
    }
}
