<?php

namespace Tests\Tenant;

use App\Facades\Settings;
use App\Jobs\RefreshFilterIndexJob;
use App\Listeners\TriggerFilterReindex;
use Carbon\Carbon;
use Illuminate\Support\Facades\Bus;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TenantTestCase;

class TriggerFilterReindexTest extends TenantTestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        Bus::fake();
        Carbon::setTestNow('2026-04-28 12:00:00');
    }

    protected function tearDown(): void
    {
        Carbon::setTestNow();
        parent::tearDown();
    }

    public static function frequencyWindowProvider(): array
    {
        return [
            'every-hour'      => ['every-hour',      90],
            'every-two-hours' => ['every-two-hours', 180],
            'daily'           => ['daily',           1500],
            'twice-daily'     => [null,              780],
            'unknown'         => ['something-else',  780],
        ];
    }

    #[DataProvider('frequencyWindowProvider')]
    public function testDispatchesWithWindowDerivedFromFrequency(?string $frequency, int $expectedMinutes): void
    {
        if ($frequency !== null) {
            Settings::update('stock-sync-frequency', $frequency);
        }

        new TriggerFilterReindex()->handle((object) []);

        $assertion = function (RefreshFilterIndexJob $job) use ($expectedMinutes) {
            $reflection = new \ReflectionProperty($job, 'since');
            $since = $reflection->getValue($job);

            return $since !== null
                && $since->equalTo(Carbon::now()->subMinutes($expectedMinutes));
        };

        Bus::assertDispatched(RefreshFilterIndexJob::class, $assertion);
    }
}
