<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Mtc\MercuryDataModels\User;

class CreateMtcUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:create-mtc
        {--email= : Email address for the new account}
        {--name= : Display name for the new account}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new user account with the mtc role';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(): int
    {
        $email = $this->option('email') ?: $this->ask('Email');

        while ($error = $this->emailError($email)) {
            $this->error($error);
            $email = $this->ask('Email');
        }

        $name = $this->option('name') ?: $this->ask('Name');
        $password = $this->secret('Password');

        $validator = Validator::make(
            compact('name', 'password'),
            [
                'name' => 'required|string|max:255',
                'password' => 'required|string|min:8',
            ]
        );

        if ($validator->fails()) {
            foreach ($validator->errors()->all() as $error) {
                $this->error($error);
            }

            return Command::FAILURE;
        }

        /** @var User $user */
        $user = User::query()->create([
            'name' => $name,
            'email' => $email,
            'password' => Hash::make($password),
        ]);

        $user->assignRole(config('mtc_login.mtc_user_role'));

        $this->info("Created mtc user {$user->email} (#{$user->id}).");

        return Command::SUCCESS;
    }

    /**
     * Validate the email, returning the first error message or null when valid.
     */
    protected function emailError(?string $email): ?string
    {
        $validator = Validator::make(
            ['email' => $email],
            ['email' => 'required|email|unique:' . User::class . ',email']
        );

        return $validator->fails() ? $validator->errors()->first('email') : null;
    }
}
