<?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;

/**
 * Filters branch-scoped queries to the current user's allowed branches.
 * Delegates the actual decision tree to
 * {@see CurrentContext::restrictToAccessibleBranches()} — the single place
 * that logic lives, shared with any raw/manual query that can't rely on a
 * model's global scope (e.g. a join that starts from a different base model).
 *
 * Super-admins/all-branch-access users pass through unfiltered unless an
 * explicit X-Branch-Id has been resolved — in that case we still filter so
 * their reports show the selected branch only.
 *
 * Bypass when needed: `Model::withoutGlobalScope(BranchScope::class)`.
 */
class BranchScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        if (! Auth::check()) {
            return;
        }

        app(CurrentContext::class)->restrictToAccessibleBranches($builder, $model->getTable().'.branch_id');
    }
}
