<?php

namespace App\Listeners;

use App\ScheduledTasks\ScheduledTaskRepository;
use App\ScheduledTasks\StockSyncSchedule;
use Mtc\MercuryDataModels\ScheduledTask;
use Mtc\MercuryDataModels\Setting;

/**
 * Keeps the read-only "Stock sync" system task in step with the stock-sync-frequency
 * setting. The task is not editable in the UI, so this restores the old behaviour where
 * changing the frequency setting immediately changed the sync cadence.
 */
class RefreshStockSyncTaskSchedule
{
    public function __construct(private readonly ScheduledTaskRepository $repository)
    {
    }

    public function handle(Setting $setting): void
    {
        if ($setting->config_key !== 'stock-sync-frequency') {
            return;
        }

        $task = ScheduledTask::query()
            ->where('managed_by', ScheduledTask::MANAGED_BY_SYSTEM)
            ->whereHas('actions', fn ($query) => $query->where('action_type', 'stock-sync'))
            ->first();

        if (!$task) {
            return;
        }

        $task->update([
            'schedule_rules' => StockSyncSchedule::rulesForFrequency($setting->value),
        ]);

        $this->repository->refreshSchedule($task->fresh());
    }
}
