<?php

namespace App\Jobs;

use App\Models\Schedule;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Services\ScheduleService;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class StartScheduleJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        public int $scheduleId
    ) {}

    public function handle()
    {
        try {
            $schedule = Schedule::find($this->scheduleId);

            $date_cleaned = Carbon::parse($schedule->date)->format('Y-m-d');

            if (! $schedule) {
                return;
            }

            Log::channel('schedule_start_jobs')->info('Verificando status do agendamento id: '.$schedule->id);
            Log::channel('schedule_start_jobs')->info('Status do agendamento: '.$schedule->status);

            if ($schedule->status !== 'paid') {
                return;
            }

            Log::channel('schedule_start_jobs')->info('Verificando data');
            Log::channel('schedule_start_jobs')->info('Data do agendamento: '.$date_cleaned);
            Log::channel('schedule_start_jobs')->info('Data atual: '.now()->toDateString());

            if ($date_cleaned > now()->toDateString()) {
                return;
            }

            Log::channel('schedule_start_jobs')->info('Verificando horário');
            Log::channel('schedule_start_jobs')->info('Horário do agendamento: '.$schedule->start_time);
            Log::channel('schedule_start_jobs')->info('Horário atual: '.now()->toTimeString());

            $start_date_time = Carbon::parse($date_cleaned.' '.$schedule->start_time);

            if ($start_date_time > now()) {
                return;
            }

            Log::channel('schedule_start_jobs')->info('Validado com sucesso, atualizado agendamento id: '.$schedule->id.' para status iniciado');

            $schedule->update([
                'status' => 'started',
            ]);

            $date_time_dispatch = Carbon::parse($date_cleaned.' '.$schedule->end_time);

            FinishScheduleJob::dispatch($schedule->id)->delay($date_time_dispatch);

            // dispatch de teste em local
            // FinishScheduleJob::dispatch($schedule->id)->delay(now()->addSeconds(15));
        } catch (\Exception $e) {
            Log::channel('schedule_start_jobs')->error('Erro ao iniciar agendamento id: '.$this->scheduleId.'. Erro: '.$e->getMessage());

            return;
        }
    }
}
