<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Validator;

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


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a user to access exposed API only';

    private array $rules = [
        'name' => ['required', 'min:4', 'unique:users,name'],
        'email' => ['required', 'email', 'unique:users,email'],
    ];

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $validator = Validator::make([
            'name' => $this->argument('name'),
            'email' => $this->argument('email'),
        ], $this->rules);

        try {
            $userData = $validator->validated();

            $userData['password'] = bcrypt(date('Y-m-d H:i:s'));

            /** @var User $user */
            $user = User::factory()->create($userData);
            $token = $user->createToken('manual-cli', ['build:make'], Date::create(2030))->plainTextToken;

            $this->info('User created. Token: ' . $token);

        } catch (\Exception $e) {
            $this->error("ERROR: {$e->getMessage()} [Code: {$e->getCode()}]");
            return 1;
        }

        return 0;
    }
}
