<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\MembershipApiToken;

class CleanupExpiredTokens extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'membership:cleanup-tokens {--force : Force cleanup without confirmation}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clean up expired membership API tokens from the database';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $expiredCount = MembershipApiToken::where('expires_at', '<', now())->count();
        
        if ($expiredCount === 0) {
            $this->info('No expired tokens found.');
            return Command::SUCCESS;
        }

        if (!$this->option('force')) {
            if (!$this->confirm("Found {$expiredCount} expired tokens. Do you want to delete them?")) {
                $this->info('Operation cancelled.');
                return Command::SUCCESS;
            }
        }

        $deletedCount = MembershipApiToken::cleanupExpiredTokens();
        
        $this->info("Successfully cleaned up {$deletedCount} expired API tokens.");
        
        // Also deactivate tokens that are about to expire (within 5 minutes)
        $soonExpiringCount = MembershipApiToken::where('is_active', true)
            ->where('expires_at', '<', now()->addMinutes(5))
            ->update(['is_active' => false]);
        
        if ($soonExpiringCount > 0) {
            $this->info("Deactivated {$soonExpiringCount} tokens expiring soon.");
        }
        
        return Command::SUCCESS;
    }
}
