<?php

namespace App\Modules\Sales\Services;

use App\Modules\Sales\DTOs\SalesAllocateLineResult;
use Illuminate\Support\Facades\DB;

final class SalesReservationService
{
    public function __construct(
        private readonly SalesReservationAllocateHandler $allocateHandler,
    ) {}

    public function allocateLineQuantity(
        int $tenantId,
        int $salesOrderId,
        int $lineId,
        string $quantity,
        string $idempotencyKey,
        ?string $correlationId,
        ?int $actorUserId,
    ): SalesAllocateLineResult {
        $attempts = (int) config('inventory.transaction_attempts', 5);

        return DB::transaction(function () use (
            $tenantId,
            $salesOrderId,
            $lineId,
            $quantity,
            $idempotencyKey,
            $correlationId,
            $actorUserId,
        ): SalesAllocateLineResult {
            return $this->allocateHandler->execute(
                $tenantId,
                $salesOrderId,
                $lineId,
                $quantity,
                $idempotencyKey,
                $correlationId,
                $actorUserId,
            );
        }, $attempts);
    }
}
