<?php

namespace App\Modules\Admin\Tenancy\Services;

use Closure;

/**
 * Request/job-scoped tenant context to make tenant isolation work outside HTTP auth().
 *
 * This intentionally does not infer tenant from arbitrary inputs. Callers must explicitly
 * initialize it (HTTP middleware / queue jobs) to avoid accidental cross-tenant access.
 */
final class TenantContext
{
    private ?int $tenantId = null;

    public function tenantId(): ?int
    {
        return $this->tenantId;
    }

    public function hasTenant(): bool
    {
        return $this->tenantId !== null;
    }

    public function setTenantId(?int $tenantId): void
    {
        $this->tenantId = $tenantId !== null ? (int) $tenantId : null;
    }

    /**
     * @template T
     * @param  Closure():T  $callback
     * @return T
     */
    public function runForTenant(int $tenantId, Closure $callback): mixed
    {
        $prev = $this->tenantId;
        $this->tenantId = (int) $tenantId;
        try {
            return $callback();
        } finally {
            $this->tenantId = $prev;
        }
    }
}

