<?php

namespace App\Models\Scopes;

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

/**
 * Global scope for the Branch model itself: every Branch query is narrowed
 * to the current user's accessible branches. This is what makes every
 * Branch-derived surface — relationship selects, table filters, belongsTo
 * label loads, the BranchResource listing, the tenant-side user
 * warehouses picker — respect the access list in one place.
 *
 * Deliberately uses {@see CurrentContext::accessibleBranchIds()} only, never
 * {@see CurrentContext::branchId()} — that method resolves the ambient branch
 * by querying Branch, which would re-enter this scope and recurse.
 *
 * Bypass when a surface must show branches beyond the user's own list (e.g.
 * a stock transfer's destination): `Branch::query()->withoutGlobalScope(
 * AccessibleBranchScope::class)` or the equivalent on a belongsTo eager
 * load. Central/landlord context passes through (mirroring TenantScope and
 * BranchScope).
 */
class AccessibleBranchScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        if (! Auth::check()) {
            return;
        }

        if (app(CurrentContext::class)->isCentral()) {
            return;
        }

        $ids = app(CurrentContext::class)->accessibleBranchIds();
        if ($ids !== null) {
            $builder->whereIn($model->getTable().'.id', $ids);
        }
    }
}