<?php

namespace Tests\Feature;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class PruneExpiredDatabaseCacheCommandTest extends TestCase
{
    use RefreshDatabase;

    public function test_expired_database_cache_entries_are_pruned_without_removing_live_entries(): void
    {
        $this->freezeTime();
        config(['cache.default' => 'database']);
        Cache::put('platform-discovery:expired', ['data' => []], 60);
        Cache::put('meta-quota-cooldown:expired', now()->timestamp + 60, 60);
        Cache::put('other-expired', 'old', 60);
        $this->travel(61)->seconds();
        Cache::put('platform-discovery:live', ['data' => [['id' => '123']]], 300);
        $this->assertSame(4, DB::table('cache')->count());

        $this->artisan('cache:prune-expired-database')
            ->expectsOutput('Deleted 3 expired cache entries.')
            ->assertSuccessful();

        $this->assertSame(1, DB::table('cache')->count());
        $this->assertSame(['data' => [['id' => '123']]], Cache::get('platform-discovery:live'));
    }

    public function test_non_database_cache_store_is_left_untouched(): void
    {
        config(['cache.default' => 'array']);
        DB::table('cache')->insert(['key' => 'expired', 'value' => 'old', 'expiration' => now()->subMinute()->timestamp]);

        $this->artisan('cache:prune-expired-database')
            ->expectsOutput('Skipped: the active cache store is not database-backed.')
            ->assertSuccessful();

        $this->assertSame(1, DB::table('cache')->count());
    }

    public function test_database_cache_cleanup_is_scheduled_daily(): void
    {
        $task = collect(app(Schedule::class)->events())
            ->first(fn ($event): bool => str_contains($event->command, 'cache:prune-expired-database'));

        $this->assertNotNull($task);
        $this->assertSame('10 3 * * *', $task->expression);
    }
}
