<?php

namespace App\Listeners;

use App\Contracts\SalesChannel;
use App\IntegrationRepository;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;

class TriggerSalesChannelExport
{
    use DispatchesJobs;

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        $this->getIntegrations()
            ->each(function (SalesChannel $channel) {
                try {
                    $channel->runScheduledExport();
                } catch (\Exception $exception) {
                    Log::error(tenant('id') . " - Failed to export to {$channel->name()} aster stock sync", [
                        'message' => $exception->getMessage(),
                    ]);
                }
            });
    }

    private function getIntegrations()
    {
        return (new IntegrationRepository())
            ->getEnabledForType('sales-channels')
            ->filter(fn($integration) => !empty($integration['class']))
            ->filter(fn($integration) => !($integration['global'] ?? false))
            ->map(fn($integration) => App::make($integration['class']))
            ->reject(fn(SalesChannel $provider) => method_exists($provider, 'runAfterStockSync')
                && $provider->runAfterStockSync() === false);
    }
}
