<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class ResetAllUserPasswords extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'skinbase:reset-all-passwords {--chunk=500 : Chunk size for processing} {--yes : Skip confirmation}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Reset all user passwords to secure random values and flag for password reset.';

    public function handle(): int
    {
        if (! $this->option('yes') && ! $this->confirm('This will replace every user password with a secure random value and mark accounts as needing a reset. Continue?')) {
            $this->info('Aborted. No changes were made.');
            return 0;
        }

        $chunk = (int) $this->option('chunk');
        $count = DB::table('users')->count();
        if ($count === 0) {
            $this->info('No users found.');
            return 0;
        }

        $bar = $this->output->createProgressBar($count);
        $bar->start();

        DB::table('users')->orderBy('id')->chunkById($chunk, function ($rows) use ($bar) {
            foreach ($rows as $row) {
                DB::table('users')->where('id', $row->id)->update([
                    'password' => Hash::make(Str::random(64)),
                    'needs_password_reset' => true,
                    'updated_at' => now(),
                ]);
                $bar->advance();
            }
        }, 'id');

        $bar->finish();
        $this->newLine(2);
        $this->info('All user passwords reset and accounts flagged for password reset.');

        return 0;
    }
}
