<?php

namespace App\Console\Commands;

use Mtc\MercuryDataModels\Enums\QueueProcessType;
use App\IntegrationRepository;
use App\Jobs\RunImageSyncTask;
use App\Modules\ImageSync\ImageSync;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\QueueProcessLog;

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) {
                $this->runImageSync($class);
            });
        return 0;
    }

    private function runImageSync(ImageSync $class): void
    {
        $className = get_class($class);
        $this->info('Running ' . $className);

        $processLog = QueueProcessLog::start(
            QueueProcessType::ImageSync,
            $className,
            ['tenant' => tenant('id')]
        );

        try {
            $class->sync();
            $processLog->markCompleted();
        } catch (Exception $exception) {
            $processLog->markFailed($exception->getMessage(), [
                'exception_class' => get_class($exception),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
                'trace' => array_slice($exception->getTrace(), 0, 10),
            ]);

            $this->error('Failed: ' . $exception->getMessage());
        }
    }
}
