<?php

namespace App\Console\Commands;

use App\Jobs\SendRoadObservationToNikarayan;
use App\Models\RoadObserved;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SendRoadObservationToNikarayanCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'road-observation:send-to-nikarayan';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'send road observation to nikarayan from 1 farvardin 1403 to 14 mehr 1403';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $count = 0;
        $this->info("Dispatching jobs with a delay between each...");

        DB::transaction(function () use (&$count) {
            RoadObserved::query()
                ->whereBetween('StartTime_DateTime_fa', ['1403-01-01 00:00:00', '1403-07-13 23:59:59'])
                ->chunkById(50, function ($roads) use (&$count) {
                    foreach ($roads as $road) {
                        $road->update(['status' => 1]);
                        SendRoadObservationToNikarayan::dispatch($road);
                        Log::channel('road_observation_problem')->info("Job for Road Observed ID {$road->id} scheduled.");
                        $this->info("Scheduled job for Road ID: {$road->id}");
                        $count +=1;
                    }
                });
        });

        $this->info("{$count} item's sent successfully");
    }
}
