<?php

namespace App\Console\Commands;

use App\Enums\BookingStatus;
use App\Enums\BookingItemStatus;
use App\Models\Booking;
use App\Models\BookingItem;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CleanOldPendingBookings extends Command
{
    protected $signature = 'bookings:clean-old-pending';
    protected $description = 'Cancel bookings that are pending for more than 1 hour';

    public function handle()
    {
        // Get the bookings that need to be updated
        $bookingsToUpdate = Booking::query()
            ->where('status', BookingStatus::PENDING)
            ->where('created_at', '<', now()->subHourS(24))
            ->get();

        $updated = 0;
        $updatedItems = 0;

        foreach ($bookingsToUpdate as $booking) {
            // Update the booking
            $booking->status = BookingStatus::CANCELED;
            $booking->save();
            $updated++;

            // Update related booking items
            $items = $booking->items()->where('status', BookingItemStatus::PENDING)->get();
            foreach ($items as $item) {
                $item->status = BookingItemStatus::CANCELED;
                $item->save();
                $updatedItems++;
            }
        }

        $this->info("Updated {$updated} old pending bookings to cancelled status.");
        $this->info("Updated {$updatedItems} related booking items to cancelled status.");

        return 0;
    }
}
