<?php

namespace App\Console\Commands;

use App\Models\Auth\User;
use App\Services\JwtService;
use Illuminate\Console\Command;

class RefreshUserJwts extends Command
{
    protected $signature = 'app:refresh-user-jwts';
    protected $description = 'Refresh user JWTs that are older than the configured refresh interval.';

    public function handle(JwtService $jwtService): int
    {
        $refreshInterval = (int) config('jwt.refresh_interval', 3600);
        $threshold = now()->subSeconds($refreshInterval);

        User::query()
            ->where(function ($query) use ($threshold) {
                $query->whereNull('user_jwt')
                    ->orWhereNull('user_jwt_issued_at')
                    ->orWhere('user_jwt_issued_at', '<=', $threshold);
            })
            ->chunkById(100, function ($users) use ($jwtService) {
                foreach ($users as $user) {
                    $jwtService->forceRefresh($user);
                }
            });

        $this->info('Stale user JWTs refreshed successfully.');

        return self::SUCCESS;
    }
}