<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use App\IntegrationRepository;
use App\Jobs\RunImageSyncTask;
use Illuminate\Console\Command;

class SyncVehicleImages extends Command
{
    /**
     * 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()
    {
        $now = Carbon::now();
        $duringWorkWindow = $now->hour >= 6 && $now->hour <= 22;
        if (!$duringWorkWindow) {
            return 0;
        }
        $this->repository->getEnabledForType('image-sync')
            ->filter(fn ($integration) => ! empty($integration['class']))
            ->each(function ($integration) {
                $this->info('Dispatching ' . $integration['class']);
                RunImageSyncTask::dispatch($integration['class']);
            });

        return 0;
    }
}
