<?php

namespace App\Models\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;

class TenantScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     */
    public function apply(Builder $builder, Model $model): void
    {
        if (Auth::hasUser() && filament()->getTenant()) {
            $tenant = filament()->getTenant();

            // For many-to-many relationships, we need to join the pivot table
            $builder->whereHas('orgs', function ($query) use ($tenant) {
                $query->where('orgs.id', $tenant->id);
            });
        }
    }
}
