<?php

namespace App\Jobs;

use App\Models\Schedule;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public function handle(): void
    {
        $today = today();
        $now = now();

        // Agendamentos aceitos ou pendente cujo a data já passou.
        Schedule::query()
            ->whereIn('status', ['accepted', 'pending'])
            ->whereDate('date', '<', $today)
            ->update([
                'status' => 'cancelled',
                'cancel_text' => 'Agendamento expirado',
            ]);


        // Agendamentos pendentes de hoje cujo horário já terminou.
        Schedule::query()
            ->where('status', 'pending')
            ->whereDate('date', $today)
            ->whereNotNull('end_time')
            ->whereRaw("CAST(end_time AS time) < ?", [$now->format('H:i:s')])
            ->update([
                'status' => 'cancelled',
                'cancel_text' => 'Agendamento expirado',
            ]);
    }
}
