<?php

namespace App\Console\Commands;

use App\Models\Central\CentralAdmin;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class MakeCentralAdmin extends Command
{
    protected $signature = 'central:make-admin
        {name : Full name}
        {email : Login email}
        {--password= : Password (generated if omitted)}';

    protected $description = 'Create a master-control (landlord) administrator.';

    public function handle(): int
    {
        $email = Str::lower(trim((string) $this->argument('email')));

        $validator = Validator::make(['email' => $email], [
            'email' => ['required', 'email', 'unique:central_admins,email'],
        ]);

        if ($validator->fails()) {
            $this->error($validator->errors()->first());

            return self::FAILURE;
        }

        $password = (string) ($this->option('password') ?: Str::password(16));

        CentralAdmin::create([
            'name' => (string) $this->argument('name'),
            'email' => $email,
            'password' => $password,
            'is_active' => true,
        ]);

        $this->info('Central admin created.');
        $this->table(['Email', 'Password'], [[$email, $password]]);

        return self::SUCCESS;
    }
}
