<?php

namespace App\Domains\Catalog\Services;

use App\Domains\Cart\Services\ExpireCartReservationsService;
use App\Domains\Purchase\Services\CheckoutService;
use Illuminate\Support\Facades\Log;
use Throwable;

class ExpireStockReservationsService
{
    public function __construct(
        private readonly CheckoutService $checkout,
        private readonly ExpireCartReservationsService $carts,
    ) {}

    /**
     * @return array{purchases: int, cart_items: int}
     */
    public function expireOverdue(): array
    {
        $expiredPurchases = null;
        $expiredCartItems = null;

        try {
            $expiredPurchases = $this->checkout->expireOverduePurchases();
            $expiredCartItems = $this->carts->expireOverdue();

            Log::channel('commands')->info('Stock reservation cleanup completed.', [
                'command' => 'reservations:expire',
                'expired_purchases' => $expiredPurchases,
                'expired_cart_items' => $expiredCartItems,
                'total_expired' => $expiredPurchases + $expiredCartItems,
            ]);

            return [
                'purchases' => $expiredPurchases,
                'cart_items' => $expiredCartItems,
            ];
        } catch (Throwable $exception) {
            Log::channel('commands')->error('Stock reservation cleanup failed.', [
                'command' => 'reservations:expire',
                'expired_purchases' => $expiredPurchases,
                'expired_cart_items' => $expiredCartItems,
                'exception' => $exception,
            ]);

            throw $exception;
        }
    }
}
