<?php

namespace App\Console\Commands;

use App\Enums\BookingStatus;
use App\Models\Booking;
use Illuminate\Console\Command;

class MarkNoShowBookings extends Command
{
    protected $signature   = 'bookings:mark-no-show {--hours=} {--minutes=0}';
    protected $description = 'Marca como no asistidas las reservas pendientes/confirmadas que ya terminaron.';

    public function handle(): int
    {
        $hours = $this->option('hours');
        $graceMinutes = $hours !== null
            ? ((int) $hours * 60)
            : (int) $this->option('minutes');

        $cutoff = now()->subMinutes(max(0, $graceMinutes));

        $count = 0;

        Booking::query()
            ->withoutGlobalScopes()
            ->whereIn('status', ['pending', 'confirmed'])
            ->whereRaw('DATE_ADD(scheduled_at, INTERVAL duration_minutes MINUTE) <= ?', [$cutoff])
            ->eachById(function (Booking $booking) use (&$count) {
                $booking->update(['status' => BookingStatus::NoShow]);
                $count++;
            });

        $this->info("Reservas marcadas como no asistidas: {$count}");
        return self::SUCCESS;
    }
}
