<?php

namespace App\Domain\Shared\Scopes;

use App\Domain\Shared\Context\BranchScopeState;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

/**
 * Narrow a child row to the active branch through the parent that owns it.
 *
 * Line items and pivots — invoice items, POS lines, payslip items, evaluation
 * scores, kit components — have no branch of their own and should not grow
 * one: their branch is whatever their parent's is, and a denormalised copy on
 * a child row is a second source of truth that will drift the first time a
 * parent moves.
 *
 * The condition is deliberately just whereHas($relation) with no extra clause.
 * The parent already carries BranchScope, and whereHas applies the related
 * model's global scopes — so "exists a parent I am allowed to see" *is* the
 * branch condition, and it stays correct automatically if the parent's own
 * classification (strict vs shared) ever changes.
 *
 * The relation must be non-nullable. whereHas excludes rows whose parent is
 * missing, which is right for a line item and wrong for an optional link.
 */
class BranchScopeThrough implements Scope
{
    /**
     * @param  string  $relation  Eloquent relation name; dotted paths allowed.
     */
    public function __construct(private string $relation)
    {
    }

    public function apply(Builder $builder, Model $model): void
    {
        if (! app(BranchScopeState::class)->shouldFilter()) {
            return;
        }

        $builder->whereHas($this->relation);
    }
}
