<?php

namespace CouponsPlus\App\Coupon\Tree\Finders;

use CouponsPlus\App\Coupon\TestableData;
use CouponsPlus\Original\Collections\Collection;
use CouponsPlus\App\Coupon\Tree\Finders\Abilities\TestableRelationsDataFinder;

class TestablePartialRelationsDataFinderFromCollection implements TestableRelationsDataFinder
{
    protected Collection $testablePartialRelations;

    public function __construct(array $testablePartialRelations)
    {
        $this->testablePartialRelations = new Collection($testablePartialRelations);
    }

    /**
     * Returns a raw stdClass object or null
     *
     * Format of relations is:
     *
     * [
     *     { id: 'testable-abc', data: [...(the full testable data)...],  children: ['testable-partial-def'] },
     * ]
     */
    public function findParent(string $id) : ?object
    {
        $parentRelation =  $this->testablePartialRelations->find(function (object $relation) use ($id) {
            $children = new Collection($relation->children ?? []);

            return $children->contain($id);
        });

        return $parentRelation ? $parentRelation->data : null;
    }
}