<?php

namespace App\Console\Commands;

use App\Events\DeleteUnverifiedUser;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Event;

class DeleteUnverifiedUsersCommand extends Command
{
    protected $signature = 'users:delete-unverified {--timeout=86400}';
    protected $description = 'Delete unverified users older than the configured timeout (seconds).';

    public function handle(): int
    {
        $timeout = (int) $this->option('timeout');
        if ($timeout <= 0) {
            $timeout = 86400;
        }

        $cutoff = now()->subSeconds($timeout);

        $users = User::query()
            ->where('is_verified', 0)
            ->where(function ($q) use ($cutoff) {
                $q->where('updated_at', '<=', $cutoff)
                    ->orWhere(function ($sub) use ($cutoff) {
                        $sub->whereNull('updated_at')->where('created_at', '<=', $cutoff);
                    });
            })
            ->get(['id']);

        $count = 0;
        foreach ($users as $user) {
            Event::dispatch(new DeleteUnverifiedUser((int) $user->id));
            $count++;
        }

        $this->info("Dispatched delete events for {$count} unverified user(s).");

        return self::SUCCESS;
    }
}
