<?php

namespace Modules\Bms\Console;

use Illuminate\Console\Command;
use Modules\Bms\Entities\BmsBooking;
use Modules\Bms\Services\Booking\BookingService;

/**
 * Closes out bookings whose event date has passed: confirmed/contracted
 * bookings roll to "completed". When the QC module gates completion, a booking
 * with a failed/open QC inspection is left for staff to resolve.
 * Scheduled daily (see BmsServiceProvider).
 */
class CompletePastEventsCommand extends Command
{
    protected $signature = 'bms:complete-past-events {--days=1 : Grace days after the event date}';

    protected $description = 'Auto-complete BMS bookings whose event date has passed';

    public function handle(BookingService $bookings): int
    {
        $cutoff = now()->subDays((int) $this->option('days'))->toDateString();

        $due = BmsBooking::whereIn('status', ['confirmed', 'contracted'])
            ->whereNotNull('event_date')
            ->whereDate('event_date', '<=', $cutoff)
            ->get();

        $completed = 0;
        foreach ($due as $booking) {
            if (! $this->qcClear($booking)) {
                continue;
            }
            $bookings->markCompleted($booking);
            $completed++;
        }

        $this->info("[BMS] Completed {$completed} past-event booking(s).");

        return self::SUCCESS;
    }

    /** True when QC does not block completion (no QC module → always clear). */
    protected function qcClear(BmsBooking $booking): bool
    {
        $qc = '\Modules\Bms\Services\Qc\QcService';
        if (! class_exists($qc)) {
            return true;
        }
        return app($qc)->passesCompletionGate($booking);
    }
}
