<?php

namespace App\Listeners;

use App\Events\StockSyncFinished;
use App\IntegrationRepository;
use App\Modules\ImageSync\ImageSync;
use Illuminate\Support\Facades\App;

class TriggerImageSyncAfterStockSyncProcess
{
    /**
     * Create the event listener.
     */
    public function __construct(private readonly IntegrationRepository $repository)
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(StockSyncFinished $event): void
    {
        $this->repository->getEnabledForType('image-sync')
            ->filter(fn($integration) => !empty($integration['class']))
            ->map(fn($data) => App::make($data['class']))
            ->filter(fn($class) => $class instanceof ImageSync)
            ->each(function (ImageSync $class) {
                try {
                    $class->sync();
                } catch (\Throwable $exception) {
                    // do nothing
                }
            });
    }
}
