<?php

namespace App\Support;

use Illuminate\Database\Eloquent\Builder;

final class GeoTenantScope
{
    public static function apply(Builder $builder, ?int $tenantId, string $table = ''): Builder
    {
        $prefix = $table !== '' ? $table.'.' : '';

        return $builder->where(function (Builder $q) use ($tenantId, $prefix): void {
            $q->whereNull($prefix.'tenant_id');
            if ($tenantId !== null && $tenantId > 0) {
                $q->orWhere($prefix.'tenant_id', $tenantId);
            }
        });
    }
}
