<?php

namespace App\Models\Scopes;

use App\Tenancy\TenantManager;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

/**
 * Auto-filter every query by the current tenant's company_id.
 * No-op when no tenant is resolved (central panel context).
 */
class TenantScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        $tenant = app(TenantManager::class);

        if (! $tenant->isResolved()) {
            // Fail-safe: no tenant set → return zero rows (prevents accidental
            // cross-tenant leak). Use withoutGlobalScopes() in central panel
            // to query across all tenants intentionally.
            $builder->whereRaw('0 = 1');
            return;
        }

        $builder->where(
            $model->getTable() . '.company_id',
            $tenant->currentId()
        );
    }
}
