<?php

namespace App\Console\Commands;

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

class ExpireUnpaidBookings extends Command
{
    protected $signature = 'bookings:expire-unpaid';

    protected $description = 'Expire unpaid appointments after their payment deadline or scheduled time';

    public function handle(BookingRepositoryInterface $bookings, BookingNotificationService $notifications): int
    {
        $timezone = config('desxpert.booking_timezone');
        $now = Carbon::now($timezone);

        foreach ($bookings->getUnpaidExpirationCandidates($now->toDateString()) as $booking) {
            try {
                $scheduledAt = Carbon::parse("{$booking->date} {$booking->time}", $timezone);
            } catch (\Throwable) {
                continue;
            }

            if ($booking->unpaidDeadlinePassed() && $bookings->expireUnpaidBooking($booking->id)) {
                $booking->status = 'expired';
                $notifications->bookingExpiredUnpaid($booking);
            }
        }

        return self::SUCCESS;
    }
}
