<?php

namespace App\Console\Commands;

use Illuminate\Cache\DatabaseStore;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

#[Signature('cache:prune-expired-database')]
#[Description('Delete expired entries from the active database cache store')]
class PruneExpiredDatabaseCacheCommand extends Command
{
    public function handle(): int
    {
        $store = Cache::getStore();

        if (! $store instanceof DatabaseStore) {
            $this->info('Skipped: the active cache store is not database-backed.');

            return self::SUCCESS;
        }

        $table = (string) config('cache.stores.'.config('cache.default').'.table', 'cache');
        $deleted = $store->getConnection()->table($table)
            ->where('expiration', '<=', now()->timestamp)
            ->delete();

        $this->info("Deleted {$deleted} expired cache entries.");

        return self::SUCCESS;
    }
}
