<?php

namespace Tests\Tenant;

use App\Listeners\RefreshStockSyncTaskSchedule;
use Database\Seeders\Tenant\StockSyncSystemTaskSeeder;
use Illuminate\Support\Carbon;
use Mtc\MercuryDataModels\ScheduledTask;
use Mtc\MercuryDataModels\Setting;
use Tests\DatabaseTestCase;

class RefreshStockSyncTaskScheduleTest extends DatabaseTestCase
{
    // The listener refreshes the slot profile, a central table, so it needs the master DB.
    #[\Override]
    protected function tearDown(): void
    {
        Carbon::setTestNow();
        parent::tearDown();
    }

    public function testListenerReschedulesTheSystemTaskForTheNewFrequency(): void
    {
        (new StockSyncSystemTaskSeeder())->run();
        $task = ScheduledTask::query()->where('managed_by', ScheduledTask::MANAGED_BY_SYSTEM)->first();
        // Seeder falls back to twice-daily default when the setting is absent
        $this->assertEquals(['09:00', '17:00'], collect($task->schedule_rules)->pluck('time')->toArray());

        $setting = new Setting(['config_key' => 'stock-sync-frequency', 'type' => 'string', 'value' => 'daily']);
        app(RefreshStockSyncTaskSchedule::class)->handle($setting);

        $this->assertEquals(['08:00'], collect($task->fresh()->schedule_rules)->pluck('time')->toArray());
    }

    public function testEveryHourFrequencyExpandsToTheWorkingWindow(): void
    {
        (new StockSyncSystemTaskSeeder())->run();

        $setting = new Setting(['config_key' => 'stock-sync-frequency', 'type' => 'string', 'value' => 'every-hour']);
        app(RefreshStockSyncTaskSchedule::class)->handle($setting);

        $times = collect(ScheduledTask::query()->where('managed_by', ScheduledTask::MANAGED_BY_SYSTEM)
            ->first()->schedule_rules)->pluck('time')->values();
        $this->assertEquals('06:00', $times->first());
        $this->assertEquals('22:00', $times->last());
        $this->assertCount(17, $times);
    }

    public function testListenerIgnoresOtherSettingsAndMissingTask(): void
    {
        // No system task: must not error
        app(RefreshStockSyncTaskSchedule::class)
            ->handle(new Setting(['config_key' => 'stock-sync-frequency', 'type' => 'string', 'value' => 'daily']));
        $this->assertEquals(0, ScheduledTask::query()->count());

        // Unrelated setting: must not touch the task
        (new StockSyncSystemTaskSeeder())->run();
        app(RefreshStockSyncTaskSchedule::class)
            ->handle(new Setting(['config_key' => 'something-else', 'type' => 'string', 'value' => 'x']));
        $task = ScheduledTask::query()->where('managed_by', ScheduledTask::MANAGED_BY_SYSTEM)->first();
        $this->assertEquals(['09:00', '17:00'], collect($task->schedule_rules)->pluck('time')->toArray());
    }
}
