<?php

namespace App\Console\Commands;

use App\Repositories\Interfaces\BookingRepositoryInterface;
use App\Services\BookingNotificationService;
use Carbon\Carbon;
use Illuminate\Console\Command;

class SendAppointmentReminders extends Command
{
    protected $signature = 'bookings:send-reminders';

    protected $description = 'Send push notifications five minutes before paid, accepted appointments';

    public function handle(
        BookingNotificationService $notifications,
        BookingRepositoryInterface $bookings,
    ): int {
        $timezone = config('desxpert.booking_timezone');
        $now = now($timezone);
        $windowStart = $now->copy()->addMinutes(5)->startOfMinute();
        $windowEnd = $windowStart->copy()->endOfMinute();

        $candidates = $bookings->getReminderCandidates(array_values(array_unique([
            $windowStart->toDateString(),
            $windowEnd->toDateString(),
        ])));

        foreach ($candidates as $booking) {
            $startsAt = Carbon::createFromFormat(
                'Y-m-d H:i',
                $booking->date.' '.$booking->time,
                $timezone,
            );

            if (! $startsAt->betweenIncluded($windowStart, $windowEnd)) {
                continue;
            }

            $notifications->appointmentReminder($booking);
            $bookings->update(['reminder_sent_at' => now()], $booking->id);
        }

        return self::SUCCESS;
    }
}
