<?php

namespace App\Console\Commands;

use App\IntegrationRepository;
use App\Jobs\RunImageSyncTask;
use App\Modules\ImageSync\ImageSync;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\App;

class SyncVehicleImages extends Command
{
    use DispatchesJobs;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:vehicle-images';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync vehicle images from providers that provide a feed (e.g. Autoload IT)';

    public function __construct(private readonly IntegrationRepository $repository)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $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 {
                    $this->info('Running ' . get_class($class));
                    $class->sync();
                } catch (\Throwable $exception) {
                    $this->error($exception->getMessage());
                }
            });
        return 0;
    }
}
