<?php

namespace App\Console\Commands;

use App\Models\Role;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;

class MakeSuperAdmin extends Command
{
    protected $signature = 'trafficpumper:make-super-admin';

    protected $description = 'İlk TrafficPumper süper admin hesabını güvenli şekilde oluşturur';

    public function handle(): int
    {
        $name = (string) $this->ask('Ad Soyad');
        $email = mb_strtolower((string) $this->ask('E-posta'));
        if (User::where('email', $email)->exists()) {
            $this->error('Bu e-posta zaten kullanımda. Mevcut hesap otomatik olarak yükseltilmedi.');

            return self::FAILURE;
        }
        $password = (string) $this->secret('Şifre');
        $confirmation = (string) $this->secret('Şifre tekrar');
        $validator = Validator::make(compact('name', 'email', 'password') + ['password_confirmation' => $confirmation], [
            'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'email'],
            'password' => ['required', 'confirmed', Password::defaults()],
        ]);
        if ($validator->fails()) {
            foreach ($validator->errors()->all() as $error) {
                $this->error($error);
            }

            return self::FAILURE;
        }
        $user = User::create(['name' => $name, 'email' => $email, 'password' => Hash::make($password)]);
        $user->forceFill(['email_verified_at' => now()])->saveQuietly();
        $user->roles()->attach(Role::where('name', 'super_admin')->sole());
        $this->info('Süper admin hesabı oluşturuldu.');

        return self::SUCCESS;
    }
}
