<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Laravel\Passport\Token;
use Laravel\Passport\TokenRepository;
use Laravel\Passport\RefreshTokenRepository;

class RevokeExpiredTokens extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'revoke:expiredTokens';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This is the common command for revoking expired passport tokens';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(TokenRepository $tokenRepository, RefreshTokenRepository $refreshTokenRepository)
    {
        parent::__construct();
        $this->tokenRepository = $tokenRepository;
        $this->refreshTokenRepository = $refreshTokenRepository;
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->line("Starting Revoke Process");

        $expiredTokens  = Token::where('expires_at', '<=', date('Y-m-d H:i:s'))->where('revoked', 0)->get();
        // dd($expiredTokens);

        foreach ($expiredTokens as $token) {
            // $token->revoked = 1;
            // $token->save();

            $this->tokenRepository->revokeAccessToken($token->id);
            $this->refreshTokenRepository->revokeRefreshTokensByAccessTokenId($token->id);
        }

        $this->line("Revoke Process Completed");
    }
}
