<?php

namespace App\Services\Inventory;

use Illuminate\Contracts\Cache\Lock;
use Illuminate\Support\Facades\Cache;

class InventoryConcurrencyLimiter
{
    public function __construct(private readonly int $lockTtlSeconds = 900) {}

    public function acquireGlobalSlot(): ?Lock
    {
        $max = (int) config('tenantpilot.inventory_sync.concurrency.global_max', 2);
        $max = max(0, $max);

        return $this->acquireSlot('inventory_sync:global:slot:', $max);
    }

    public function acquireTenantSlot(int $tenantId): ?Lock
    {
        $max = (int) config('tenantpilot.inventory_sync.concurrency.per_tenant_max', 1);
        $max = max(0, $max);

        return $this->acquireSlot("inventory_sync:tenant:{$tenantId}:slot:", $max);
    }

    private function acquireSlot(string $prefix, int $max): ?Lock
    {
        for ($slot = 0; $slot < $max; $slot++) {
            $lock = Cache::lock($prefix.$slot, $this->lockTtlSeconds);

            if ($lock->get()) {
                return $lock;
            }
        }

        return null;
    }
}
