<?php

namespace App\Console\Commands;

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

class CreateUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:create {--e|email= : The email address of the user}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new user';

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

        $name = $this->ask("Please provide a name");
        $surname = $this->ask("Please provide a surname");

        if (empty($email)) {
            $email = $this->ask("Please provide an email address");
        }

        if (empty($password)) {
            // TODO: have a way to hide the input and do a confirm password input
            $password = $this->secret("Please provide a password");
        }

        try {
            User::create([
                'name'     => trim($name),
                'surname'  => trim($surname),
                'email'    => trim($email),
                'password' => Hash::make(trim($password)),
            ]);

            $this->info("$email created successfully.");
            return 0;
        } catch (\Exception $e) {
            $this->error('Unable to create your user.');
            $this->line($e->getMessage());
            return 1;
        }
    }
}
