<?php

namespace App\Console\Commands;

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

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

    public function handle(): int
    {
        $graceMinutes = max(0, (int) $this->option('minutes'));
        $count = 0;

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

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

        return self::SUCCESS;
    }
}
