<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Services\InventoryService;
use Illuminate\Console\Command;

class CancelExpiredAwaitingPaymentOrders extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'orders:cancel-expired-awaiting-payment';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Cancel unpaid awaiting_payment orders older than 4 hours and release reservations';

    /**
     * Execute the console command.
     */
    public function handle(InventoryService $inventoryService): int
    {
        $cutoff = now()->subHours(4);
        $cancelledCount = 0;

        Order::query()
            ->where('status', Order::STATUS_AWAITING_PAYMENT)
            ->where('payment_method', 'online')
            ->whereIn('payment_status', [Order::PAYMENT_PENDING, Order::PAYMENT_FAILED])
            ->where('created_at', '<=', $cutoff)
            ->orderBy('id')
            ->chunkById(100, function ($orders) use ($inventoryService, &$cancelledCount) {
                foreach ($orders as $order) {
                    $inventoryService->releaseByOrderId($order->id);

                    $updated = Order::whereKey($order->id)
                        ->where('status', Order::STATUS_AWAITING_PAYMENT)
                        ->update([
                            'status' => Order::STATUS_CANCELLED,
                            'payment_status' => Order::PAYMENT_FAILED,
                        ]);

                    if ($updated > 0) {
                        $cancelledCount++;
                    }
                }
            });

        $this->info("Cancelled {$cancelledCount} expired awaiting payment order(s).");

        return Command::SUCCESS;
    }
}
