<?php

namespace Tests\Feature\Console;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Str;
use Tests\TestCase;

class ScheduleConfigurationTest extends TestCase
{
    public function test_storage_and_checkout_commands_are_scheduled(): void
    {
        Artisan::call('schedule:list', [
            '--json' => true,
            '--no-interaction' => true,
        ]);

        $tasks = json_decode(Artisan::output(), true, 512, JSON_THROW_ON_ERROR);

        $this->assertScheduledCommand($tasks, 'storage:monitor', '*/5 * * * *');
        $this->assertScheduledCommand($tasks, 'storage:check-upload-queues', '*/5 * * * *');
        $this->assertScheduledCommand($tasks, 'storage:archive-pending', '0 1 * * *');
        $this->assertScheduledCommand($tasks, 'checkout:send-reminders', '0 * * * *');
    }

    /**
     * @param  array<int, array<string, mixed>>  $tasks
     */
    private function assertScheduledCommand(array $tasks, string $command, string $expression): void
    {
        foreach ($tasks as $task) {
            $taskCommand = (string) ($task['command'] ?? '');
            if ($taskCommand !== '' && Str::contains($taskCommand, $command)) {
                $this->assertSame($expression, $task['expression'] ?? null);

                return;
            }
        }

        $this->fail(sprintf('Scheduled command not found: %s', $command));
    }
}
