<?php

namespace App\Console\Commands;

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

class ResetPassword extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'password:reset {--i|id= : The ID of the user} {--e|email= : The email address of the user} {--p|password}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Reset the password for a given user';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

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

        if (! empty($id) && empty($email)) {
            $column = 'id';
            $value = $id;
        } elseif (empty($id) && ! empty($email)) {
            $column = 'email';
            $value = $email;
        } else {
            $column = strtolower($this->choice('What column would you like to search by?', ['ID', 'Email']));
            $value = $this->ask("Please provide an $column to search for");
        }

        $user = User::where($column, $value)->first();
        if (! $user) {
            $this->error('Unable to find a user matching your input.');
            return 1;
        }

        if (empty($password)) {
            $password = $this->secret('What is the new password?');
        }
        try {
            $user->update(['password' => Hash::make($password)]);
            $this->info("User {$user->id} ({$user->email}) password update successful!");
            return 0;
        } catch (\Exception $e) {
            $this->error('Unable to set the password!');
            $this->line($e->getMessage());
            return 1;
        }
    }
}
