<?php

namespace App\Console\Commands;

use App\Models\Booking;
use App\Notifications\BookingReminder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Notification;

class SendBookingReminders extends Command
{
    protected $signature   = 'bookings:send-reminders {--hours=24}';
    protected $description = 'Envía recordatorios a clientes para reservas próximas en N horas (default 24).';

    public function handle(): int
    {
        $hours  = (int) $this->option('hours');
        $window = now();
        $target = $window->copy()->addHours($hours);

        // Reservas que arrancan dentro del rango +/-15 min al objetivo y aún no recibieron recordatorio.
        $bookings = Booking::query()
            ->withoutGlobalScopes()
            ->with(['customer', 'service', 'company'])
            ->whereIn('status', ['pending', 'confirmed'])
            ->whereNull('reminder_sent_at')
            ->whereBetween('scheduled_at', [
                $target->copy()->subMinutes(15),
                $target->copy()->addMinutes(15),
            ])
            ->get();

        $count = 0;
        foreach ($bookings as $booking) {
            if (! $booking->customer?->email) {
                continue;
            }
            try {
                Notification::route('mail', $booking->customer->email)
                    ->notify(new BookingReminder($booking));
                $booking->update(['reminder_sent_at' => now()]);
                $count++;
            } catch (\Throwable $e) {
                $this->error("Error en reserva {$booking->code}: {$e->getMessage()}");
            }
        }

        $this->info("Recordatorios enviados: {$count}");
        return self::SUCCESS;
    }
}
