<?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()
    {
        $this->removeExpiredStandardReservations();
        $this->removeExpiredFreeReservations();
    }

    /**
     * Paid reservations expire a configurable number of days after confirmation, and only when
     * the dealership has opted in to automatic removal.
     */
    private function removeExpiredStandardReservations(): void
    {
        if (
            empty(Settings::get('sales-reservation-remove-expired'))
            || empty(Settings::get('sales-reservation-expiry-days'))
        ) {
            return;
        }

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

    /**
     * Free reservations carry their own calculated expiry datetime and are always released once
     * it passes, independent of the paid-reservation removal toggle.
     */
    private function removeExpiredFreeReservations(): void
    {
        Reservation::query()
            ->where('type', Reservation::TYPE_FREE)
            ->whereIn('status', ['pending', 'confirmed'])
            ->whereNotNull('expires_at')
            ->where('expires_at', '<', Carbon::now())
            ->each(function ($reservation) {
                $this->repository->cancel($reservation, false);
            });
    }
}
