<?php

namespace App\Console\Commands;

use App\Facades\Settings;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Mtc\VehicleReservations\Reservation;
use Mtc\VehicleReservations\ReservationRepository;

class RemoveExpiredReservations extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'reservations:remove-expired';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove expired reservations';

    public function __construct(private readonly ReservationRepository $repository)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if (
            empty(Settings::get('sales-reservation-remove-expired'))
            || empty(Settings::get('sales-reservation-expiry-days'))
        ) {
            return;
        }

        Reservation::query()
            ->where('status', 'confirmed')
            ->where('confirmed_at', '<', Carbon::now()->subDays(Settings::get('sales-reservation-expiry-days')))
            ->each(function ($reservation) {
                $this->repository->cancel($reservation, false);
            });
    }
}
