<?php

namespace App\Listeners;

use App\Events\StockSyncFinished;
use App\Jobs\RunScheduledTaskJob;
use Illuminate\Support\Carbon;
use Mtc\MercuryDataModels\ScheduledTask;
use Mtc\MercuryDataModels\ScheduledTaskRun;

class TriggerScheduledTasksOnPlatformEvent
{
    /**
     * The event fires once per provider and per import map, so a task's optional
     * event_filter narrows it to one provider; without a filter it fires for all.
     */
    public function handle(StockSyncFinished $event): void
    {
        ScheduledTask::query()
            ->enabled()
            ->where('trigger_type', ScheduledTask::TRIGGER_AFTER_EVENT)
            ->where('event', 'stock-sync-finished')
            ->where(function ($query) use ($event) {
                $query->whereNull('event_filter')
                    ->orWhere('event_filter', $event->provider);
            })
            ->each(function (ScheduledTask $task) {
                $run = $task->runs()->create([
                    'status' => ScheduledTaskRun::STATUS_PENDING,
                    'scheduled_for' => Carbon::now(),
                    'trigger' => ScheduledTaskRun::TRIGGER_AFTER_EVENT,
                ]);

                RunScheduledTaskJob::dispatch($run);
            });
    }
}
